class FenwickTree: def __init__(self, size): self.n = size self.tree = [0] * (self.n + 2) # Adding +2 to avoid overflow issues def update(self, index, delta=1): while index <= self.n: self.tree[index] += delta index += index & -index def query(self, index): res = 0 while index > 0: res += self.tree[index] index -= index & -index return res def count_inversion(arr): m = len(arr) if m == 0: return 0 ft = FenwickTree(m) ans = 0 for x in reversed(arr): ans += ft.query(x) ft.update(x + 1) return ans def main(): import sys input = sys.stdin.read().split() ptr = 0 N, K = int(input[ptr]), int(input[ptr+1]) ptr += 2 a = list(map(int, input[ptr:ptr+N])) ptr += N sorted_a = sorted(a) value_to_pos = {val: idx for idx, val in enumerate(sorted_a)} possible = True for idx in range(N): original_pos = idx + 1 # 1-based x = a[idx] target_pos = value_to_pos[x] + 1 # 1-based if (original_pos - 1) % K != (target_pos - 1) % K: possible = False break if not possible: print(-1) return orbits = [[] for _ in range(K)] for original_pos in range(1, N + 1): r = (original_pos - 1) % K orbits[r].append(original_pos) total = 0 for r in range(K): pos_list = orbits[r] if not pos_list: continue original_list = [a[i-1] for i in pos_list] sorted_values = [sorted_a[i-1] for i in pos_list] value_map = {val: i for i, val in enumerate(sorted_values)} permutation = [value_map[val] for val in original_list] inv_count = count_inversion(permutation) total += inv_count print(total) if __name__ == "__main__": main()