#include #include #include #include #include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; const int INF = 100000000; struct edge {int to, cap, rev;}; class FordFolkerson{ public: FordFolkerson(int n){ N = n; G = vector>(n, vector()); used = vector(n, false); } void add_edge(int from, int to, int cap){ G[from].push_back((edge{to, cap, (int)G[to].size()})); G[to].push_back((edge{from, 0, (int)G[from].size()-1})); } int max_flow(int s, int t){ int flow = 0; while(true){ clear_used(); int f = dfs(s, t, INF); if(f == 0){ break; } flow += f; } return flow; } private: vector> G; vector used; int N; void clear_used(){ for(int i = 0; i < N; i++) used[i] = false; } int dfs(int v, int t, int f){ if(v == t) return f; used[v] = true; for(int i = 0; i < G[v].size(); i++){ edge &e = G[v][i]; if(!used[e.to] && e.cap > 0){ int d = dfs(e.to, t, min(f, e.cap)); if(d > 0){ e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } }; using P = pair; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int h, w; cin >> h >> w; vector> a(h, vector(w)); map idx; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ cin >> a[i][j]; if(a[i][j] == 0) continue; // row if(idx.count(P(i, a[i][j])) == 0) idx[P(i, a[i][j])] = idx.size(); // col if(idx.count(P(h+j, a[i][j])) == 0) idx[P(h+j, a[i][j])] = idx.size(); } } int m = idx.size(); FordFolkerson mf(2+m); int s = 0, t = m+1; vector used(m+1); for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ if(a[i][j] == 0) continue; int v1 = idx[P(i, a[i][j])]+1; int v2 = idx[P(h+j, a[i][j])]+1; if(!used[v1]) mf.add_edge(s, v1, 1); if(!used[v2]) mf.add_edge(v2, t, 1); used[v1] = true; used[v2] = true; mf.add_edge(v1, v2, 1); } } cout << mf.max_flow(s, t) << endl; }