import sys sys.setrecursionlimit(10**7) n, k = map(int, input().split()) a = list(map(int, input().split())) b = sorted(a) ans = 0 for i in range(k): cur = [] need = [] j = i while j < n: cur.append(a[j]) need.append(b[j]) j += k if sorted(cur) != sorted(need): print(-1) sys.exit() # tạo mapping value -> list vị trí trong need from collections import defaultdict, deque pos = defaultdict(deque) for idx, val in enumerate(need): pos[val].append(idx) # xây permutation perm = [] for val in cur: perm.append(pos[val].popleft()) # đếm cycle visited = [False]*len(perm) for j in range(len(perm)): if visited[j]: continue cycle = 0 x = j while not visited[x]: visited[x] = True x = perm[x] cycle += 1 if cycle > 1: ans += cycle - 1 print(ans)