#include #include #include #include #include #include #include #include #include using namespace std; using ull = unsigned long long; bool check(int index1,int index2,int k) { int sub = abs(index1 - index2); if(sub % k == 0) return true; else return false; } bool Fillter(vector>& checker,pair test) { for(const auto& x : checker) { if((x.first == test.first && x.second == test.second) || (x.first == test.second && x.second == test.first)) return false; } return true; } int main() { ull n,k; cin >> n >> k; vector a(n); vector> checker; for(auto&& x : a) { cin >> x; } vector sorted_a = a; sort(sorted_a.begin(),sorted_a.end()); if(k >= n) { if(sorted_a == a) { cout << 0 << endl; return 0; } else { cout << -1 << endl; return 0; } } ull count = 0; ull i = 0; for(int i =0; i < n; ++i) { auto iter1 = find(a.begin(), a.end(),a.at(i)); int index1 = distance(a.begin(), iter1); auto iter2 = find(sorted_a.begin(), sorted_a.end(),a.at(i)); int index2 = distance(sorted_a.begin(), iter2); if(!check(index1,index2,k)) { cout << -1 << endl; return 0; } } while(a != sorted_a) { if(sorted_a.at(i) != a.at(i)) { if(i+k < n) { if(Fillter(checker,make_pair(a.at(i),a.at(i+k)))) { checker.emplace_back(make_pair(a.at(i),a.at(i+k))); swap(a.at(i),a.at(i+k)); ++count; } else { cout << -1 << endl; return 0; } } } ++i; if(i+k == n) i = 0; } cout << count << endl; }