#include <bits/stdc++.h> using namespace std; using ll = long long; ll solve(int n, int k, vector<int> a) { ll res = 0; vector<int> exists(n + 1); int next_free_pos = 0; for (int i = 0; i < n && next_free_pos < k; i++) { if (!exists[a[i]]) { res += i - next_free_pos; next_free_pos++; exists[a[i]] = 1; } } if (next_free_pos < k) { return -1; } else { return res; } } int main() { ios_base::sync_with_stdio(false); int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } cout << solve(n, k, a) << 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 | #include <bits/stdc++.h> using namespace std; using ll = long long; ll solve(int n, int k, vector<int> a) { ll res = 0; vector<int> exists(n + 1); int next_free_pos = 0; for (int i = 0; i < n && next_free_pos < k; i++) { if (!exists[a[i]]) { res += i - next_free_pos; next_free_pos++; exists[a[i]] = 1; } } if (next_free_pos < k) { return -1; } else { return res; } } int main() { ios_base::sync_with_stdio(false); int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } cout << solve(n, k, a) << endl; } |