#include <iostream> using namespace std; long long n, k, a, t[500005], r, x, wyn; bool czy[500005], b[500005], s; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> k; for(int i=0; i<n; ++i) { cin >> a; t[i]=a; if(!czy[t[i]]) { r++; czy[t[i]]=1; } } if(r<k) { cout << -1; return 0; } k--; b[t[0]]=1; for(int i=1; i<n; ++i) { if(t[i]!=t[i-1] && b[t[i]]==0 && s==0) { k--; b[t[i]]=1; } else if(b[t[i]]==1) { x++; s=1; } else if(b[t[i]]==0 && s==1) { b[t[i]]=1; wyn=wyn+x; k--; } if(!k) break; } if(k!=0) { cout << -1; return 0; } cout << wyn; 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 | #include <iostream> using namespace std; long long n, k, a, t[500005], r, x, wyn; bool czy[500005], b[500005], s; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> k; for(int i=0; i<n; ++i) { cin >> a; t[i]=a; if(!czy[t[i]]) { r++; czy[t[i]]=1; } } if(r<k) { cout << -1; return 0; } k--; b[t[0]]=1; for(int i=1; i<n; ++i) { if(t[i]!=t[i-1] && b[t[i]]==0 && s==0) { k--; b[t[i]]=1; } else if(b[t[i]]==1) { x++; s=1; } else if(b[t[i]]==0 && s==1) { b[t[i]]=1; wyn=wyn+x; k--; } if(!k) break; } if(k!=0) { cout << -1; return 0; } cout << wyn; return 0; } |