#include<bits/stdc++.h>
using namespace std;
int n, k;
set<int> x;
int tab[500007];
int res = 0;
int main()
{
cin.tie(0);
ios::sync_with_stdio(0);
cin >> n >> k;
for(int i = 0; i < n; i++) cin >> tab[i];
int z = 0;
for(int i = 0; i < k; i++)
{
if(!x.count(tab[i]))
{
x.insert(tab[i]);
}
else
{
while(x.count(tab[z]))
{
z++;
}
if(z > n-1)
{
cout << -1;
return 0;
}
x.insert(tab[z]);
swap(tab[i], tab[z]);
res += z-i;
}
}
cout << res;
}
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 | #include<bits/stdc++.h> using namespace std; int n, k; set<int> x; int tab[500007]; int res = 0; int main() { cin.tie(0); ios::sync_with_stdio(0); cin >> n >> k; for(int i = 0; i < n; i++) cin >> tab[i]; int z = 0; for(int i = 0; i < k; i++) { if(!x.count(tab[i])) { x.insert(tab[i]); } else { while(x.count(tab[z])) { z++; } if(z > n-1) { cout << -1; return 0; } x.insert(tab[z]); swap(tab[i], tab[z]); res += z-i; } } cout << res; } |
English