using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; using System.Linq; using System.IO; class Magatro { static Scanner sc = new Scanner(); static int N, K; static int[] a; static void Main() { N = sc.NextInt(); K = sc.NextInt(); int[][] a = new int[K][]; for(int i = 0; i < K; i++) { if (N % K > i) { a[i] = new int[N / K+1]; } else { a[i] = new int[N / K]; } } for(int i = 0; i < N; i++) { a[i % K][i / K] = sc.NextInt(); } int cnt = 0; for(int i = 0; i < K; i++) { cnt += BubbleSort(ref a[i]); } int[] ans = Arr(a); if (Sorted(ans)) { Console.WriteLine(cnt); } else { Console.WriteLine(-1); } } static int BubbleSort(ref int[] array) { int cnt = 0; for(int i = 0; i < array.Length-1; i++) { for(int j = array.Length-1; j > i; j--) { if (array[j] < array[j - 1]) { Swap(ref array[j], ref array[j - 1]); cnt++; } } } return cnt; } static int[] Arr(int[][] a) { int[] res = new int[N]; for(int i = 0; i < N; i++) { res[i] = a[i % K][i / K]; } return res; } static bool Sorted(int[] array) { for(int i = 0; i < array.Length-1; i++) { if (array[i] > array[i + 1]) { return false; } } return true; } static void Swap(ref int a,ref int b) { int temp = a; a = b; b = temp; } } public class Scanner { public string[] S; private int Index; private char Separator; public Scanner(char separator=' ') { Index = 0; Separator = separator; } public string Next() { string result; if (S == null || Index >= S.Length) { S = Line(); Index = 0; } result = S[Index]; Index++; return result; } private string[] Line() { return Console.ReadLine().Split(Separator); } public int NextInt() { return int.Parse(Next()); } public double NextDouble() { return double.Parse(Next()); } public long NextLong() { return long.Parse(Next()); } }