#include #include using namespace std; using namespace atcoder; #define rep(i,n)for (int i = 0; i < int(n); ++i) #define rrep(i,n)for (int i = int(n)-1; i >= 0; --i) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() template void chmax(T& a, const T& b) {a = max(a, b);} template void chmin(T& a, const T& b) {a = min(a, b);} using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; // https://ei1333.github.io/algorithm/bipartite-matching.html struct Bipartite_Matching { vector< vector< int > > graph; vector< int > match, alive, used; int timestamp; Bipartite_Matching(int n) { timestamp = 0; graph.resize(n); alive.assign(n, 1); used.assign(n, 0); match.assign(n, -1); } void add_edge(int u, int v) { graph[u].push_back(v); graph[v].push_back(u); } bool dfs(int v) { used[v] = timestamp; for(int i = 0; i < graph[v].size(); i++) { int u = graph[v][i], w = match[u]; if(alive[u] == 0) continue; if(w == -1 || (used[w] != timestamp && dfs(w))) { match[v] = u; match[u] = v; return (true); } } return (false); } int bipartite_matching() { int ret = 0; for(int i = 0; i < graph.size(); i++) { if(alive[i] == 0) continue; if(match[i] == -1) { ++timestamp; ret += dfs(i); } } return (ret); } }; int main() { ios::sync_with_stdio(false); cin.tie(0); int h, w; cin >> h >> w; vector> d(500001); rep(i, h) rep(j, w) { int a; cin >> a; if (a) d[a].emplace_back(i, j); } int ans = 0; for(auto& ps: d) if (!ps.empty()) { Bipartite_Matching bm(h + w); for(auto [i, j]: ps) { bm.add_edge(i, h + j); } ans += bm.bipartite_matching(); } cout << ans << '\n'; }