#include<bits/stdc++.h>
#define limN 500005
using namespace std;
int tab[limN];
bool vis[limN];
queue<int> q;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n, k; cin >> n >> k;
for(int i = 0; i < n; i++)
cin >> tab[i];
long long ans = 0;
int rozne = 0;
for(int i = 0; i < n; i++) {
if(!vis[tab[i]]) {
rozne++;
vis[tab[i]] = true;
if(!q.empty()) {
// cout << q.front() << '\n';
ans += i-q.front();
int pom = tab[i];
tab[i] = tab[q.front()];
tab[q.front()] = pom;
// for(int i = 0; i < n; i++)
// cout << tab[i] << " ";
q.pop();
q.push(i);
}
}
else
q.push(i);
if(rozne == k){
// cout << "upa";
cout << ans; return 0;
}
}
cout << -1;
}
/*
6 4
1 1 1 2 3 4
*/
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 | #include<bits/stdc++.h> #define limN 500005 using namespace std; int tab[limN]; bool vis[limN]; queue<int> q; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k; cin >> n >> k; for(int i = 0; i < n; i++) cin >> tab[i]; long long ans = 0; int rozne = 0; for(int i = 0; i < n; i++) { if(!vis[tab[i]]) { rozne++; vis[tab[i]] = true; if(!q.empty()) { // cout << q.front() << '\n'; ans += i-q.front(); int pom = tab[i]; tab[i] = tab[q.front()]; tab[q.front()] = pom; // for(int i = 0; i < n; i++) // cout << tab[i] << " "; q.pop(); q.push(i); } } else q.push(i); if(rozne == k){ // cout << "upa"; cout << ans; return 0; } } cout << -1; } /* 6 4 1 1 1 2 3 4 */ |
English