#include <bits/stdc++.h> using namespace std; #define st first #define nd second #define iamspeed ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0) long long n, k, r, il, t[500005], wk[500005], res; int main() { iamspeed; cin >> n >> k; r = k + 1; for(int i = 1 ; i <= n ; i++) { cin >> t[i]; } for(int i = 1 ; i <= k ; i++) { wk[t[i]]++; } for(int i = k ; i > 0 ; i--) { if(wk[t[i]] > 1) { r--; res += r - i; wk[t[i]]--; il++; } } for(int i = k + 1; i <= n && r != k + 1; i++) { if(!wk[t[i]]) { wk[t[i]] = 1; res += i - r; r++; } } if(r == k + 1) cout << res << endl; else cout << -1 << 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 | #include <bits/stdc++.h> using namespace std; #define st first #define nd second #define iamspeed ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0) long long n, k, r, il, t[500005], wk[500005], res; int main() { iamspeed; cin >> n >> k; r = k + 1; for(int i = 1 ; i <= n ; i++) { cin >> t[i]; } for(int i = 1 ; i <= k ; i++) { wk[t[i]]++; } for(int i = k ; i > 0 ; i--) { if(wk[t[i]] > 1) { r--; res += r - i; wk[t[i]]--; il++; } } for(int i = k + 1; i <= n && r != k + 1; i++) { if(!wk[t[i]]) { wk[t[i]] = 1; res += i - r; r++; } } if(r == k + 1) cout << res << endl; else cout << -1 << endl; } |