#include <iostream> #include <vector> using namespace std; int main() { int n, k; cin >> n >> k; vector<int> a(n), to_remove(n, 0); vector<int> taken(n + 1, 0); // 0 element unused for (int i = 0; i < n; i++) cin >> a[i]; int taken_cnt = 0; int last_taken_idx = -1; for (int i = 0; i < n; i++) { if (taken[a[i]] == 0) { taken[a[i]] = 1; taken_cnt++; } else { to_remove[i] = 1; } if (taken_cnt == k) { last_taken_idx = i; break; } } if (taken_cnt < k) { cout << "-1" << endl; } else { int res = 0; for (int i = last_taken_idx; i >= 0; i--) { if (to_remove[i]) { res += last_taken_idx - i; last_taken_idx--; } } 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 | #include <iostream> #include <vector> using namespace std; int main() { int n, k; cin >> n >> k; vector<int> a(n), to_remove(n, 0); vector<int> taken(n + 1, 0); // 0 element unused for (int i = 0; i < n; i++) cin >> a[i]; int taken_cnt = 0; int last_taken_idx = -1; for (int i = 0; i < n; i++) { if (taken[a[i]] == 0) { taken[a[i]] = 1; taken_cnt++; } else { to_remove[i] = 1; } if (taken_cnt == k) { last_taken_idx = i; break; } } if (taken_cnt < k) { cout << "-1" << endl; } else { int res = 0; for (int i = last_taken_idx; i >= 0; i--) { if (to_remove[i]) { res += last_taken_idx - i; last_taken_idx--; } } cout << res << endl; } } |