#include using namespace std; #define rep(i, n) for (int i = 0; i < n; i++) #define rep2(i, x, n) for (int i = x; i <= n; i++) #define rep3(i, x, n) for (int i = x; i >= n; i--) #define each(e, v) for (auto &e : v) #define pb push_back #define eb emplace_back #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define sz(x) (int)x.size() using ll = long long; using pii = pair; using pil = pair; using pli = pair; using pll = pair; const int MOD = 1000000007; // const int MOD = 998244353; const int inf = (1 << 30) - 1; const ll INF = (1LL << 60) - 1; template bool chmax(T &x, const T &y) { return (x < y) ? (x = y, true) : false; }; template bool chmin(T &x, const T &y) { return (x > y) ? (x = y, true) : false; }; struct io_setup { io_setup() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout << fixed << setprecision(15); } } io_setup; struct Bipartite_Matching { vector> es; vector d, match; vector used, used2; const int n, m; Bipartite_Matching(int n, int m) : es(n), d(n), match(m), used(n), used2(n), n(n), m(m) {} void add_edge(int u, int v) { es[u].push_back(v); } void _bfs() { fill(begin(d), end(d), -1); queue que; for (int i = 0; i < n; i++) { if (!used[i]) que.emplace(i), d[i] = 0; } while (!que.empty()) { int i = que.front(); que.pop(); for (auto &e : es[i]) { int j = match[e]; if (j != -1 && d[j] == -1) { que.emplace(j), d[j] = d[i] + 1; } } } } bool _dfs(int now) { used2[now] = true; for (auto &e : es[now]) { int u = match[e]; if (u == -1 || (!used2[u] && d[u] == d[now] + 1 && _dfs(u))) { match[e] = now, used[now] = true; return true; } } return false; } int bipartite_matching() { fill(begin(match), end(match), -1), fill(begin(used), end(used), false); int ret = 0; while (true) { _bfs(); fill(begin(used2), end(used2), false); int flow = 0; for (int i = 0; i < n; i++) { if (!used[i] && _dfs(i)) flow++; } if (flow == 0) break; ret += flow; } return ret; } }; int main() { int H, W; cin >> H >> W; int MAX = 500000; vector> ps(MAX + 1); rep(i, H) { rep(j, W) { int A; cin >> A; ps[A].eb(i, j); } } vector cx(H, 0), cy(W, 0); int sx = 0, sy = 0; ll ans = 0; Bipartite_Matching G(H, W); rep3(i, MAX, 1) { if (ps[i].empty()) continue; if (sz(ps[i]) == 1) { ans++; continue; } each(e, ps[i]) { auto [x, y] = e; G.add_edge(x, y); } ans += G.bipartite_matching(); each(e, ps[i]) G.es[e.first].clear(); } cout << ans << '\n'; }