// Validator #include "testlib.h" #include #include #include #include using namespace std; #include int main(int argc, char **argv) { registerValidation(argc, argv); int M = inf.readInt(2, 10000000); inf.readSpace(); int K = inf.readInt(1, 400000 / M); inf.readEoln(); const int N = M * K; vector A(N); for (int i = 0; i < N; ++i) { A[i] = inf.readInt(0, M - 1); if (i + 1 < N) { inf.readSpace(); } else { inf.readEoln(); } } inf.readEof(); vector ord(N); vector freq(M); vector> v2i(M); for (int i = 0; i < N; ++i) { cin >> A[i]; ord[i] = A[i] + freq[A[i]] * M; v2i[A[i]].push_back(i); freq[A[i]]++; } assert(freq == vector(M, K)); long long current = 0; atcoder::fenwick_tree bit(N); for (int i = 0; i < N; ++i) { current += bit.sum(ord[i], N); bit.add(ord[i], 1); } long long ret = current; vector> prvs(K); for (int i = 0; i < N; ++i) prvs.at(ord[i] / M).push_back(i); for (auto &v : prvs) sort(v.begin(), v.end()); for (auto &is : v2i) { for (int t = 0; t < K; ++t) { int i = is.at(t); int nlo = lower_bound(prvs[t].begin(), prvs[t].end(), i) - prvs[t].begin(); int nhi = M - 1 - nlo; current += nhi - nlo; } ret = min(ret, current); } cout << ret << '\n'; }