#include <bits/stdc++.h>
using namespace std;
int W[501000];
list<int> T;
list<int>::iterator it;
list<int>::iterator cit;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,k;
cin>>n>>k;
int a;
for(int i=0;i<n;i++){
cin>>a;
T.push_back(a);
}
long long il=0;
long long j=0;
long long cj=0;
it = T.begin();
cit=it;
cit++;
cj++;
while(j<k){
if(cj<=j){
cit++;
cj++;
continue;
}
if(W[*it]==0){
W[*it]=1;
it++;
j++;
continue;
}
if(cit==T.end()){
cout<<-1<<"\n";
return 0;
}
while(W[*cit]==1){
cit++;
cj++;
if(cit==T.end()){
cout<<-1<<"\n";
return 0;
}
}
swap((*it),(*cit));
il=il+(cj-j);
W[*it]=1;
it++;
j++;
}
cout<<il<<"\n";
}
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 | #include <bits/stdc++.h> using namespace std; int W[501000]; list<int> T; list<int>::iterator it; list<int>::iterator cit; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,k; cin>>n>>k; int a; for(int i=0;i<n;i++){ cin>>a; T.push_back(a); } long long il=0; long long j=0; long long cj=0; it = T.begin(); cit=it; cit++; cj++; while(j<k){ if(cj<=j){ cit++; cj++; continue; } if(W[*it]==0){ W[*it]=1; it++; j++; continue; } if(cit==T.end()){ cout<<-1<<"\n"; return 0; } while(W[*cit]==1){ cit++; cj++; if(cit==T.end()){ cout<<-1<<"\n"; return 0; } } swap((*it),(*cit)); il=il+(cj-j); W[*it]=1; it++; j++; } cout<<il<<"\n"; } |
English