#include <iostream>
using namespace std;
constexpr int S = 5e5+7;
int n, k, cost = 0, i, j;
bool used[S];
int tab[S];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for(int l = 0; l < n; l++)
{
cin >> tab[l];
}
used[tab[0]] = true;
for(i = 1; i < k; i++)
{
if(used[tab[i]] == false)
{
used[tab[i]] = true;
}
else
{
break;
}
}
for(j = i + 1; j < n && i < k; j++)
{
while(used[tab[i]] == false && i < k)
{
used[tab[i]] = true;
i++;
}
if(i == k)
{
break;
}
if(used[tab[j]] == false)
{
cost += j - i;
used[tab[j]] = true;
i++;
}
}
if(i < k)
{
cout << -1;
}
else cout << cost;
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 | #include <iostream> using namespace std; constexpr int S = 5e5+7; int n, k, cost = 0, i, j; bool used[S]; int tab[S]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> k; for(int l = 0; l < n; l++) { cin >> tab[l]; } used[tab[0]] = true; for(i = 1; i < k; i++) { if(used[tab[i]] == false) { used[tab[i]] = true; } else { break; } } for(j = i + 1; j < n && i < k; j++) { while(used[tab[i]] == false && i < k) { used[tab[i]] = true; i++; } if(i == k) { break; } if(used[tab[j]] == false) { cost += j - i; used[tab[j]] = true; i++; } } if(i < k) { cout << -1; } else cout << cost; return 0; } |
English