class Fenwick_Tree: def __init__(self, n): self.n = n self.data = [0] * n def add(self, p, x): p += 1 while p <= self.n: self.data[p - 1] += x p += p & -p def sum(self, l, r): '''範囲[l, r)(lからr-1まで)の総和を求める''' return self._sum(r) - self._sum(l) def _sum(self, r): '''範囲[0, r)(0からr-1まで)の総和を求める''' s = 0 while r > 0: s += self.data[r - 1] r -= r & -r return s n, k = map(int, input().split()) A = list(map(int, input().split())) from bisect import bisect_left def compression(lst): sort_lst = sorted(set(lst)) compression_lst = [None for _ in range(len(lst))] ele2ind_dict = dict() for i, ele in enumerate(lst): compression_lst[i] = bisect_left(sort_lst, ele) ele2ind_dict[ele] = compression_lst[i] return sort_lst, compression_lst, ele2ind_dict _, _, ele2ind_dict = compression(A) for i in range(n): A[i] = ele2ind_dict[A[i]] ans = 0 if n > k: for i in range(k): FT = Fenwick_Tree(n) for j in range(i, n, k): a = A[j] ans += FT.sum(a, n) FT.add(a, 1) AA = A[i::k] AA.sort() idx = 0 for j in range(i, n, k): A[j] = AA[idx] idx += 1 for i in range(n - 1): if A[i] > A[i + 1]: ans = -1 break print(ans)