#include <bits/stdc++.h> #define pb push_back using namespace std; typedef long long ll; ll cntRevs(vector<ll> &v, ll a, ll b) { if (a == b) return 0; ll m = (a + b) / 2; ll res = 0; res += cntRevs(v, a, m); res += cntRevs(v, m+1, b); vector<ll> pom; ll leftI = a; ll rightI = m+1; while (leftI <= m && rightI <= b) { if (v[leftI] > v[rightI]) { pom.pb(v[rightI++]); res += m - leftI + 1; } else pom.pb(v[leftI++]); } while (leftI <= m) pom.pb(v[leftI++]); while (rightI <= b) pom.pb(v[rightI++]); for (int i = a; i <= b; ++i) { v[i] = pom[i-a]; } return res; } int main() { ios_base::sync_with_stdio(0); ll n, k; cin >> n >> k; vector<ll> v(n), ord(n, 0); map<ll, bool> exist; ll uniq = 0; ll ordId = 0; for (int i = 0; i < n; ++i) { cin >> v[i]; if (!exist[v[i]]) { uniq++; exist[v[i]] = true; ord[i] = ++ordId; } } if (uniq < k) { cout << -1 << endl; return 0; } for (int i = 0; i < ord.size(); ++i) { if (ord[i] == 0) ord[i] = ++ordId; } ll result = cntRevs(ord, 0, ord.size() - 1); cout << result << endl; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #include <bits/stdc++.h> #define pb push_back using namespace std; typedef long long ll; ll cntRevs(vector<ll> &v, ll a, ll b) { if (a == b) return 0; ll m = (a + b) / 2; ll res = 0; res += cntRevs(v, a, m); res += cntRevs(v, m+1, b); vector<ll> pom; ll leftI = a; ll rightI = m+1; while (leftI <= m && rightI <= b) { if (v[leftI] > v[rightI]) { pom.pb(v[rightI++]); res += m - leftI + 1; } else pom.pb(v[leftI++]); } while (leftI <= m) pom.pb(v[leftI++]); while (rightI <= b) pom.pb(v[rightI++]); for (int i = a; i <= b; ++i) { v[i] = pom[i-a]; } return res; } int main() { ios_base::sync_with_stdio(0); ll n, k; cin >> n >> k; vector<ll> v(n), ord(n, 0); map<ll, bool> exist; ll uniq = 0; ll ordId = 0; for (int i = 0; i < n; ++i) { cin >> v[i]; if (!exist[v[i]]) { uniq++; exist[v[i]] = true; ord[i] = ++ordId; } } if (uniq < k) { cout << -1 << endl; return 0; } for (int i = 0; i < ord.size(); ++i) { if (ord[i] == 0) ord[i] = ++ordId; } ll result = cntRevs(ord, 0, ord.size() - 1); cout << result << endl; } |