#include using namespace std; using ll = long long; const int INF = 1e9 + 10; const ll INFL = 4e18; template struct max_flow { max_flow(int n) { this->n = n; G = vector>>(n); } void add_edge(int u, int v, Cap c) { G[u].push_back(make_tuple(v, G[v].size(), c)); G[v].push_back(make_tuple(u, (int)G[u].size() - 1, 0)); } Cap get_max_flow(int start, int goal) { Cap ret = 0; while (true) { vector dst = calculate_distance(start); if (dst[goal] < 0) { return ret; } vector removed(n, 0); while (true) { Cap add = flowing(start, goal, numeric_limits::max(), removed, dst); if (add == 0) { break; } ret += add; } } return ret; } private: int n; vector>> G; vector calculate_distance(int start) { vector dst(n, -1); dst[start] = 0; queue que; que.push(start); while (!que.empty()) { int now = que.front(); que.pop(); for (auto [nxt, _, cap] : G[now]) { if (cap > 0 && dst[nxt] == -1) { dst[nxt] = dst[now] + 1; que.push(nxt); } } } return dst; } Cap flowing(int now, int goal, Cap limit, vector &removed, vector &dst) { if (now == goal) { return limit; } while (removed[now] < (int)G[now].size()) { auto [nxt, rev, cap] = G[now][removed[now]]; if (cap > 0 && dst[now] < dst[nxt]) { Cap flow = flowing(nxt, goal, min(limit, cap), removed, dst); if (flow > 0) { get<2>(G[now][removed[now]]) -= flow; get<2>(G[nxt][rev]) += flow; return flow; } } removed[now]++; } return 0; } }; const int MX = 5e5 + 5; int main() { int H, W; cin >> H >> W; vector> A(H, vector(W)); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> A[i][j]; } } vector>> P(MX); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { P[A[i][j]].push_back({i, j}); } } int ans = 0; for (int i = 1; i < MX; i++) { if (!P[i].empty()) { map mp; { vector idx; for (auto [x, y] : P[i]) { idx.push_back(x); idx.push_back(H + y); } idx.push_back(H + W); idx.push_back(H + W + 1); for (int x : set(idx.begin(), idx.end())) { mp[x] = mp.size(); } } max_flow mf(mp.size()); set used; for (auto [x, y] : P[i]) { mf.add_edge(mp[x], mp[H + y], 1); if (used.count(x) == 0) { mf.add_edge(mp[H + W], mp[x], 1); used.insert(x); } if (used.count(H + y) == 0) { mf.add_edge(mp[H + y], mp[H + W + 1], 1); used.insert(H + y); } } ans += mf.get_max_flow(mp[H + W], mp[H + W + 1]); } } cout << ans << endl; }