#include <bits/stdc++.h>
using namespace std;
set<int> values;
int main() {
cin.tie(0); ios_base::sync_with_stdio(false);
int n, k; cin >> n >> k;
long long result = 0;
int found = 0;
stack<int> indices_to_move;
for(int i = 0; i < n; i++) {
int v; cin >> v;
if(values.count(v)) {
indices_to_move.push(i);
}
else {
values.insert(v);
found++;
}
if(found == k) {
int offset = 0;
while(!indices_to_move.empty()) {
result += i - indices_to_move.top() - offset;
indices_to_move.pop();
offset++;
}
cout << result;
return 0;
}
}
cout << -1;
}
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 | #include <bits/stdc++.h> using namespace std; set<int> values; int main() { cin.tie(0); ios_base::sync_with_stdio(false); int n, k; cin >> n >> k; long long result = 0; int found = 0; stack<int> indices_to_move; for(int i = 0; i < n; i++) { int v; cin >> v; if(values.count(v)) { indices_to_move.push(i); } else { values.insert(v); found++; } if(found == k) { int offset = 0; while(!indices_to_move.empty()) { result += i - indices_to_move.top() - offset; indices_to_move.pop(); offset++; } cout << result; return 0; } } cout << -1; } |
English