#include #include using namespace atcoder; #define rep(i, n) for(ll i = 0; i < n; i++) #define rep2(i, m, n) for(ll i = m; i <= n; i++) #define rrep(i, m, n) for(ll i = m; i >= n; i--) #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define MAX(x) *max_element(all(x)) #define MIN(x) *min_element(all(x)) #define SZ(a) ((ll)(a).size()) using namespace std; typedef long long ll; typedef pair P; const ll mod = 1000000007; const int dx[4] = { -1, 1, 0, 0 }; const int dy[4] = { 0, 0, 1, -1 }; const int inf = 1e9 + 1; const ll INF = 1e18 + 1; const double pi = acos(-1); using Graph = vector>; Graph G; ll powll(ll a, ll b) { ll ret = 1; rep(i, b) ret *= a; return ret; } //typedef atcoder::modint1000000007 mint; //typedef atcoder::modint998244353 mint; //typedef modint mint; struct S { long long value; int size; }; using F = long long; const F ID = 8e18; S op(S a, S b) { return { a.value + b.value, a.size + b.size }; } S e() { return { 0, 0 }; } S mapping(F f, S x) { if (f != ID) x.value = f * x.size; return x; } F composition(F f, F g) { return (f == ID ? g : f); } F id() { return ID; } int a[510][510]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int h, w; cin >> h >> w; rep(i, h)rep(j, w) cin >> a[i][j]; vector> sch(500001), scw(500001); rep(i, h)rep(j, w) { sch[a[i][j]].push_back(i * w + j); scw[a[i][j]].push_back(i + j * h); } int res = 0; std::vector uh(w, { 0, 1 }); std::vector uw(h, { 0, 1 }); atcoder::lazy_segtree segh(uh); atcoder::lazy_segtree segw(uw); rep2(i, 1, 500000) { segh.apply(0, w, 0); segw.apply(0, h, 0); rep(j, SZ(sch[i])){ int p = sch[i][j] % w; segh.apply(p, p + 1, 1); } rep(j, SZ(scw[i])) { int p = scw[i][j] % h; segw.apply(p, p + 1, 1); } res += min(segh.all_prod().value, segw.all_prod().value); } cout << res << endl; }