#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using ll = long long; using std::cin; using std::cout; using std::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; } const int inf = (int)1e9 + 7; const long long INF = 1LL << 60; struct bipartite_matching { std::vector> g; std::vector r, c, vis; bipartite_matching(int h = 0, int w = 0) : g(h), r(h, -1), c(w, -1), vis(h) {} void add(int i, int j) { g[i].push_back(j); } bool dfs(int i) { if (std::exchange(vis[i], true)) return false; for (int j : g[i]) if (c[j] == -1) return r[i] = j, c[j] = i, true; for (int j : g[i]) if (dfs(c[j])) return r[i] = j, c[j] = i, true; return false; } int run() { while (true) { fill(begin(vis), end(vis), false); bool updated = false; for (int i = 0; i < (int)r.size(); ++i) if (r[i] == -1) updated |= dfs(i); if (not updated) break; } return r.size() - count(begin(r), end(r), -1); } }; void solve() { int H, W; cin >> H >> W; const int N = 500000; std::vector>> vp(N + 1); for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { int x; cin >> x; vp[x].emplace_back(i, j); } } int res = 0; for (int i = 1; i <= N; ++i) { if(vp[i].empty()) continue; bipartite_matching g(H, W); for(const auto &[h, w] : vp[i]) { g.add(h, w); } res += g.run(); } cout << res << "\n"; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); int kkt = 1; //cin >> kkt; while(kkt--) solve(); return 0; }