#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 Dinic{ public: Dinic(int n){ N = n; G = vector>(n, vector()); level = vector(n, -1); iter = vector(n, 0); } 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){ bfs(s); if(level[t] < 0) return flow; clear_iter(); int f; while(f = dfs(s, t, INF) > 0){ flow += f; } } } private: vector> G; vector level; vector iter; int N; void clear_level(){ for(int i = 0; i < N; i++) level[i] = -1; } void clear_iter(){ for(int i = 0; i < N; i++) iter[i] = 0; } int dfs(int v, int t, int f){ if(v == t) return f; for(int &i = iter[v]; i < G[v].size(); i++){ edge &e = G[v][i]; if(e.cap > 0 && level[v] < level[e.to]){ 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; } void bfs(int s){ clear_level(); queue que; level[s] = 0; que.push(s); while(!que.empty()){ int v = que.front(); que.pop(); for(edge e : G[v]){ if(e.cap > 0 && level[e.to] < 0){ level[e.to] = level[v]+1; que.push(e.to); } } } } }; 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(); Dinic 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; }