#include <iostream> #include <vector> #include <set> using namespace std; const int MAX_N = 5 * 100000; int t[MAX_N]; int t_tmp[MAX_N]; long long inv(int start, int end) { if(end <= start) { return 0; } if(end == start + 1) { if(t[end] < t[start]) { int tmp = t[end]; t[end] = t[start]; t[start] = tmp; return 1; } else { return 0; } } int mid = (end + start) / 2; long long a = inv(start, mid); long long b = inv(mid+1, end); for(int i=start; i<=end; i++) { t_tmp[i] = t[i]; } int s1 = start, s2 = mid+1; long long x = 0; int idx = start; while(s1 <= mid && s2 <= end) { if(t_tmp[s1] > t_tmp[s2]) { x += mid - s1 + 1; t[idx++] = t_tmp[s2++]; } else { t[idx++] = t_tmp[s1++]; } } while(s1 <= mid) { t[idx++] = t_tmp[s1++]; } while(s2 <= end) { t[idx++] = t_tmp[s2++]; } return a + b + x; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; set<int> dist; for (int i = 0; i < n; i++) { cin >> t[i]; dist.insert(t[i]); } if (dist.size() < k) { cout << "-1" << endl; } else { dist.clear(); int next = k; for (int i = 0; i < n; i++) { if (dist.size() < k && dist.find(t[i]) == dist.end()) { dist.insert(t[i]); t[i] = dist.size() - 1; } else { t[i] = next++; } } long long res = inv(0, n-1); cout << res << 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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | #include <iostream> #include <vector> #include <set> using namespace std; const int MAX_N = 5 * 100000; int t[MAX_N]; int t_tmp[MAX_N]; long long inv(int start, int end) { if(end <= start) { return 0; } if(end == start + 1) { if(t[end] < t[start]) { int tmp = t[end]; t[end] = t[start]; t[start] = tmp; return 1; } else { return 0; } } int mid = (end + start) / 2; long long a = inv(start, mid); long long b = inv(mid+1, end); for(int i=start; i<=end; i++) { t_tmp[i] = t[i]; } int s1 = start, s2 = mid+1; long long x = 0; int idx = start; while(s1 <= mid && s2 <= end) { if(t_tmp[s1] > t_tmp[s2]) { x += mid - s1 + 1; t[idx++] = t_tmp[s2++]; } else { t[idx++] = t_tmp[s1++]; } } while(s1 <= mid) { t[idx++] = t_tmp[s1++]; } while(s2 <= end) { t[idx++] = t_tmp[s2++]; } return a + b + x; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; set<int> dist; for (int i = 0; i < n; i++) { cin >> t[i]; dist.insert(t[i]); } if (dist.size() < k) { cout << "-1" << endl; } else { dist.clear(); int next = k; for (int i = 0; i < n; i++) { if (dist.size() < k && dist.find(t[i]) == dist.end()) { dist.insert(t[i]); t[i] = dist.size() - 1; } else { t[i] = next++; } } long long res = inv(0, n-1); cout << res << endl; } } |