#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int n, k;
long long int ans = 0;
vector<int> arr;
int kDistinct[500005];
int aux, distinct = 0;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> k;
arr.resize(n);
for (int i = 0; i < n; ++i) {
cin >> arr[i];
if (kDistinct[arr[i]] == 0) {
kDistinct[arr[i]]++;
distinct++;
}
}
if (distinct < k) {
cout << -1;
return 0;
}
for (int i = 0; i < n; ++i) {
kDistinct[arr[i]] = 0;
}
int lastJ = -1;
for (int i = 0; i < k; ++i) {
if (kDistinct[arr[i]] == 0) {
kDistinct[arr[i]]++;
} else {
if (lastJ == -1)
lastJ = i + 1;
for (int j = lastJ; j < n; ++j) {
if (kDistinct[arr[j]] == 0) {
kDistinct[arr[j]]++;
ans += j - i;
aux = arr[j];
arr[j] = arr[i];
arr[i] = aux;
lastJ = j + 1;
break;
}
}
}
}
cout << ans;
return 0;
}
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 | #include <bits/stdc++.h> #include <iostream> using namespace std; int n, k; long long int ans = 0; vector<int> arr; int kDistinct[500005]; int aux, distinct = 0; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> k; arr.resize(n); for (int i = 0; i < n; ++i) { cin >> arr[i]; if (kDistinct[arr[i]] == 0) { kDistinct[arr[i]]++; distinct++; } } if (distinct < k) { cout << -1; return 0; } for (int i = 0; i < n; ++i) { kDistinct[arr[i]] = 0; } int lastJ = -1; for (int i = 0; i < k; ++i) { if (kDistinct[arr[i]] == 0) { kDistinct[arr[i]]++; } else { if (lastJ == -1) lastJ = i + 1; for (int j = lastJ; j < n; ++j) { if (kDistinct[arr[j]] == 0) { kDistinct[arr[j]]++; ans += j - i; aux = arr[j]; arr[j] = arr[i]; arr[i] = aux; lastJ = j + 1; break; } } } } cout << ans; return 0; } |
English