#include <bits/stdc++.h>
using namespace std;
int n, k, t[500001], plusy[500001], powt[500001], k2, ile, rozne, test;
long long wynik;
int main()
{std::ios_base::sync_with_stdio(0);
cin>>n>>k;
for(int i=1; i<=n; i++){
cin>>t[i];
}
for(int i=1; i<=n; i++){
if(plusy[t[i]]==0){
plusy[t[i]]++;
rozne++;
}
}
//cout<<rozne<<" ";
if(rozne<k){
cout<<-1;
return 0;
}
for(int i=1; i<=n; i++){
plusy[i]=0;
}
for(int i=1; i<=n; i++){
if(plusy[t[i]]==0){
plusy[t[i]]++;
test++;
}
else{
powt[i]=t[i];
}
}
//cout<<test<<"\n";
//for(int i=1; i<=n; i++){
// cout<<powt[i]<<" ";
//}
//cout<<"\n";
for(int i=1; i<=n; i++){
if(t[i]!=powt[i]){
k2=i;
ile++;
}
if(ile==k){
break;
}
}
//cout<<k2<<" ";
test=k2;
for(int i=test-1; i>=1; i--){
if(powt[i]>0){
wynik+=k2-i;
k2--;
}
}
//cout<<k2<<" "<<ile<<" ";
cout<<wynik;
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 57 58 59 60 61 62 | #include <bits/stdc++.h> using namespace std; int n, k, t[500001], plusy[500001], powt[500001], k2, ile, rozne, test; long long wynik; int main() {std::ios_base::sync_with_stdio(0); cin>>n>>k; for(int i=1; i<=n; i++){ cin>>t[i]; } for(int i=1; i<=n; i++){ if(plusy[t[i]]==0){ plusy[t[i]]++; rozne++; } } //cout<<rozne<<" "; if(rozne<k){ cout<<-1; return 0; } for(int i=1; i<=n; i++){ plusy[i]=0; } for(int i=1; i<=n; i++){ if(plusy[t[i]]==0){ plusy[t[i]]++; test++; } else{ powt[i]=t[i]; } } //cout<<test<<"\n"; //for(int i=1; i<=n; i++){ // cout<<powt[i]<<" "; //} //cout<<"\n"; for(int i=1; i<=n; i++){ if(t[i]!=powt[i]){ k2=i; ile++; } if(ile==k){ break; } } //cout<<k2<<" "; test=k2; for(int i=test-1; i>=1; i--){ if(powt[i]>0){ wynik+=k2-i; k2--; } } //cout<<k2<<" "<<ile<<" "; cout<<wynik; return 0; } |
English