import sys from collections import defaultdict, deque n, k = map(int, input().split()) a = list(map(int, input().split())) b = sorted(a) # lưu tất cả vị trí của từng giá trị pos = defaultdict(deque) for i in range(n): pos[b[i]].append(i) ans = 0 for i in range(k): idx = [] j = i while j < n: idx.append(j) j += k sz = len(idx) visited = [False]*sz for j in range(sz): if visited[j]: continue c = 0 d = j while not visited[d]: visited[d] = True val = a[idx[d]] location_b = pos[val].popleft() if location_b % k != i: print(-1) sys.exit() d = (location_b - i)//k c += 1 if c > 1: ans += c - 1 print(ans)