# https://github.com/hitonanode/Polaris/blob/main/fenwick.py class Fenwick: """1-indexed Fenwick tree (Binary indexed tree) """ def __init__(self, N: int) -> None: self.sz = N + 1 self.v = [0] * (self.sz) def add(self, pos: int, val: int) -> None: while pos > 0 and pos < self.sz: self.v[pos] += val pos += pos & -pos def sum(self, pos: int) -> int: ret = 0 while pos: ret += self.v[pos] pos -= pos & -pos return ret M, K = map(int, input().split()) A = list(map(int, input().split())) N = M * K ord = [0] * N freq = [0] * M v2i = [list() for _ in range(M)] for i, a in enumerate(A): ord[i] = a + freq[a] * M v2i[a].append(i) freq[a] += 1 prvs = [list() for _ in range(K)] prvs_ord = [0] * N current = 0 bit = Fenwick(N) for i, ord_i in enumerate(ord): current += bit.sum(N) - bit.sum(ord_i) bit.add(ord_i + 1, 1) o = ord_i // M prvs_ord[i] = len(prvs[o]) prvs[o].append(i) ret = current for Is in v2i: for t, i in enumerate(Is): nlo = prvs_ord[i] nhi = M - 1 - nlo current += nhi - nlo ret = min(ret, current) print(ret)