#include #include #include #include using namespace std; using i64 = long long; using u64 = unsigned long long; using i32 = int; using u32 = unsigned int; #define rep(i,n) for(int i=0; i<(int)(n); i++) i64 inversion(vector P){ int n = P.size(); atcoder::fenwick_tree G(n); i64 ans = 0; for(auto p : P){ ans += G.sum(p+1, n); G.add(p, 1); } return ans; } vector rot_inversion(vector A){ int n = A.size(); vector X(n); rep(i,n) X[i] = i; sort(X.begin(), X.end(), [&](int l, int r)->bool{ return A[l] < A[r]; }); rep(i,n) A[X[i]] = i; vector res; res.push_back(inversion(A)); rep(i,n) res.push_back(res.back() + (n-1-2*A[i])); return res; } int main() { int N, P; cin >> P >> N; vector A(N*P); vector> pos(P); rep(i,N*P){ int a; cin >> a; A[i] = a; pos[a].push_back(i); } vector tA(N*P); rep(i,P) rep(j,N) tA[pos[i][j]] = j; i64 off = inversion(tA); vector dInv(P, off); rep(i,N){ vector subA(P); rep(j,P) subA[j] = pos[j][i]; auto tmp = rot_inversion(move(subA)); rep(j,P) dInv[j] += tmp[j]; } i64 ans = (i64)N*P*N*P; rep(i,P) ans = min(ans, dInv[i]); cout << ans << "\n"; return 0; } struct ios_do_not_sync{ ios_do_not_sync(){ std::ios::sync_with_stdio(false); std::cin.tie(nullptr); } } ios_do_not_sync_instance;