#include using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n, k; cin >> n >> k; vector a(n); for(int i = 0; i < n; i++) cin >> a[i]; vector b = a; sort(b.begin(), b.end()); // lưu tất cả vị trí của từng giá trị trong b unordered_map> pos; for(int i = 0; i < n; i++) pos[b[i]].push(i); vector perm(n); // build permutation toàn cục for(int i = 0; i < n; i++){ if(pos[a[i]].empty()){ cout << -1; return 0; } perm[i] = pos[a[i]].front(); pos[a[i]].pop(); if(perm[i] % k != i % k){ cout << -1; return 0; } } long long ans = 0; vector visited(n, false); // đếm cycle nhưng chỉ trong từng class mod k for(int i = 0; i < n; i++){ if(visited[i]) continue; int j = i; int cycle = 0; while(!visited[j]){ visited[j] = true; j = perm[j]; cycle++; } if(cycle > 1) ans += cycle - 1; } cout << ans; }