#include<bits/stdc++.h>
using namespace std;
int B[1000005];
bool W[100005];
int main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
int n, k;
cin >> n >> k;
if(k == 1){
cout << 0;
return 0;
}
for(int i=0; i<n; i++){
cin >> B[i];
}
int t = 0;
W[B[0]] = true;
int index = 2;
for(int i=1; i<k; i++){
if(W[B[i]]){
while(index < n and W[B[index]]){
index++;
}
W[B[index]] = true;
t += (index - i);
}
W[B[i]] = true;
}
if(index == n){
cout << -1;
} else {
cout << t;
}
}
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 | #include<bits/stdc++.h> using namespace std; int B[1000005]; bool W[100005]; int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); int n, k; cin >> n >> k; if(k == 1){ cout << 0; return 0; } for(int i=0; i<n; i++){ cin >> B[i]; } int t = 0; W[B[0]] = true; int index = 2; for(int i=1; i<k; i++){ if(W[B[i]]){ while(index < n and W[B[index]]){ index++; } W[B[index]] = true; t += (index - i); } W[B[i]] = true; } if(index == n){ cout << -1; } else { cout << t; } } |
English