#include <bits/stdc++.h> using namespace std; 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]; } vector <bool> First(n, false); unordered_set <int> S; int i = 0; for ( ; i < n; i++) { if (S.find(A[i]) == S.end()) { First[i] = true; S.insert(A[i]); if (S.size() == k) { break; } } } if (i == n) { cout << -1 <<endl; return 0; } long long ans = 0; int duplicates_at_the_end = 0; for (int j = i; j >= 0; j--) { if (!First[j]) { ans += (i - duplicates_at_the_end) - j; duplicates_at_the_end++; } } cout <<ans <<endl; 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 | #include <bits/stdc++.h> using namespace std; 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]; } vector <bool> First(n, false); unordered_set <int> S; int i = 0; for ( ; i < n; i++) { if (S.find(A[i]) == S.end()) { First[i] = true; S.insert(A[i]); if (S.size() == k) { break; } } } if (i == n) { cout << -1 <<endl; return 0; } long long ans = 0; int duplicates_at_the_end = 0; for (int j = i; j >= 0; j--) { if (!First[j]) { ans += (i - duplicates_at_the_end) - j; duplicates_at_the_end++; } } cout <<ans <<endl; return 0; } |