#include using namespace std; const int N = 1005; int a[N] , c[N]; pair> b[N]; bool vis[N]; int main(){ cin.tie(0)->sync_with_stdio(0); int n , k; memset(vis,false,sizeof(vis)); bool kt = true; cin >> n >> k; for(int i = 1; i <= n ; i ++){ cin >> a[i]; b[i].first = a[i]; b[i].second.first = i; } sort(b + 1, b + n + 1); int x = 0; for(int i = 1 ; i <= n ; i ++){ b[i].second.second = i; } for(int i = 1; i <= n ;i ++){ if(abs(b[i].second.second - b[i].second.first) % k != 0){ cout << -1; return 0; } } for(int i = 1; i <= n; i++){ c[b[i].second.first] = b[i].second.second; } int ans = 0; for(int i = 1; i <= n; i++){ if(vis[i] || c[i] == i) continue; int cur = i, len = 0; while(!vis[cur]){ vis[cur] = true; cur = c[cur]; len++; } ans += len - 1; } cout << ans; }