// 解説を見て実装 #include #include using namespace std; using namespace atcoder; using ll = long long; #define rep(i, n) for (int i=0; i<(int)(n); ++(i)) #define rep3(i, m, n) for (int i=(m); (i)<(int)(n); ++(i)) #define repr(i, n) for (int i=(int)(n)-1; (i)>=0; --(i)) #define rep3r(i, m, n) for (int i=(int)(n)-1; (i)>=(int)(m); --(i)) #define all(x) (x).begin(), (x).end() int main() { int h, w; cin >> h >> w; map>> aval; rep(i, h) rep(j, w) { int ai; cin >> ai; if (ai == 0) continue; aval[ai].emplace_back(i, j); } int res = 0; for (auto p : aval) { map hid, wid; rep(i, (int)(p.second.size())) { hid[p.second[i].first] = -1; wid[p.second[i].second] = -1; } auto hitr=hid.begin(), witr=wid.begin(); for (int j1=0; hitr!=hid.end(); ++hitr,++j1) hitr->second = j1; for (int j2=0; witr!=wid.end(); ++witr,++j2) witr->second = j2; int n = (int)(hid.size()) + (int)(wid.size()); mf_graph g(n+2); for (auto p2 : hid) g.add_edge(n, p2.second, 1); for (auto p2 : wid) g.add_edge((int)(hid.size())+p2.second, n+1, 1); rep(i, (int)(p.second.size())) g.add_edge(hid[p.second[i].first], (int)(hid.size())+wid[p.second[i].second], 1); res += g.flow(n, n+1); } cout << res << endl; return 0; }