import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines import numpy as np N,K = map(int,readline().split()) A = np.array(read().split(),np.int64) def Inversion(A): return sum(np.count_nonzero(A[:i] > x) for i,x in enumerate(A)) x = sum(Inversion(A[i::K]) for i in range(K)) B = np.empty_like(A) for i in range(K): B[i::K] = np.msort(A[i::K]) if np.any(B[:-1] > B[1:]): print(-1) else: print(x)