/* -*- coding: utf-8 -*- * * 1479.cc: No.1479 Matrix Eraser - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_H = 500; const int MAX_W = 500; const int MAX_N = MAX_H * MAX_W; const int MAX_M = MAX_H + MAX_W; /* typedef */ typedef vector vi; typedef vector vb; typedef map mii; struct Elm { int a, i, j; Elm() {} Elm(int _a, int _i, int _j): a(_a), i(_i), j(_j) {} bool operator<(const Elm &e) const { return a < e.a; } bool operator>(const Elm &e) const { return a > e.a; } }; /* global variables */ int as[MAX_H][MAX_W]; Elm es[MAX_N]; mii hls, vls; vi nbrs[MAX_M]; /* subroutines */ bool max_match_rec(const vi *nbrs, int u, vi &matches, vb &visited) { if (u < 0) return true; const vi &nbru = nbrs[u]; for (vi::const_iterator vit = nbru.begin(); vit != nbru.end(); vit++) { const int &v = *vit; if (! visited[v]) { visited[v] = true; if (max_match_rec(nbrs, matches[v], matches, visited)) { matches[u] = v; matches[v] = u; return true; } } } return false; } int max_match(const int n, int l, const vi *nbrs) { vi matches(n, -1); int count = 0; for (int u = 0; u < l; u++) { vb visited(n, false); if (max_match_rec(nbrs, u, matches, visited)) count++; } return count; } /* main */ int main() { int h, w; scanf("%d%d", &h, &w); int n = 0; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) { scanf("%d", as[i] + j); if (as[i][j] > 0) es[n++] = Elm(as[i][j], i, j); } sort(es, es + n, greater()); int sum = 0; for (int k0 = 0; k0 < n;) { int k1 = k0 + 1; while (k1 < n && es[k0].a == es[k1].a) k1++; if (k0 + 1 == k1) sum++; else { hls.clear(), vls.clear(); int hm = 0, vm = 0; for (int k = k0; k < k1; k++) { mii::iterator mit0 = hls.find(es[k].i); if (mit0 == hls.end()) hls[es[k].i] = hm++; mii::iterator mit1 = vls.find(es[k].j); if (mit1 == vls.end()) vls[es[k].j] = vm++; } int m = hm + vm; for (int i = 0; i < m; i++) nbrs[i].clear(); for (int k = k0; k < k1; k++) { int ki = hls[es[k].i], kj = vls[es[k].j] + hm; nbrs[ki].push_back(kj); nbrs[kj].push_back(ki); } int cnt = max_match(m, hm, nbrs); //printf("%d: %d,%d\n", es[k0].a, k1 - k0, cnt); sum += cnt; } k0 = k1; } printf("%d\n", sum); return 0; }