#include #include #include using namespace atcoder; using mint = modint998244353; using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf 1000000001 int main(){ int H,W; cin>>H>>W; vector> A(H,vector(W)); vector>> N(500001); rep(i,H){ rep(j,W){ cin>>A[i][j]; N[A[i][j]].emplace_back(i,j); } } int ans = 0; vector h(H,-1); vector w(W,-1); rep(i,N.size()){ if(i==0)continue; vector y,x; rep(j,N[i].size()){ int yy = N[i][j].first,xx = N[i][j].second; if(h[yy]==-1){ h[yy] = y.size(); y.push_back(yy); } if(w[xx]==-1){ w[xx] = x.size(); x.push_back(xx); } } sort(y.begin(),y.end()); sort(x.begin(),x.end()); mf_graph G(y.size()+x.size()+2); int S = y.size()+x.size(); int T = S+1; rep(j,N[i].size()){ int yy = N[i][j].first,xx = N[i][j].second; G.add_edge(h[yy],y.size() + w[xx],1); } rep(j,y.size()){ G.add_edge(S,j,1); } rep(j,x.size()){ G.add_edge(y.size()+j,T,1); } ans += G.flow(S,T); rep(j,N[i].size()){ int yy = N[i][j].first,xx = N[i][j].second; h[yy] = -1; w[xx] = -1; } } cout<