#include <iostream>
#include <vector>
#include <set>
int main() {
std::ios::sync_with_stdio(false);
int n, k;
std::cin >> n >> k;
std::vector<int> vines;
std::set<int> unique_to_k;
int tmp;
for (int i = 0; i < n; i++) {
std::cin >> tmp;
vines.push_back(tmp);
}
std::vector<int> to_left;
int to_right = -1;
int size = vines.size();
for (int i = 0; i < k; i++) {
// if not found
if (unique_to_k.find(vines.at(i)) == unique_to_k.end()) {
unique_to_k.insert(vines.at(i));
to_left.push_back(i);
}
// if found
else if (to_right == -1)
to_right = i;
}
std::set<int> uniques = unique_to_k;
for (int i = k; i < size; i++) {
// if not found
if (uniques.find(vines.at(i)) == uniques.end()) {
uniques.insert(vines.at(i));
to_left.push_back(i);
}
// if found
else if (to_right == -1)
to_right = i;
}
int swaps = 0;
int shifts = 0;
int to_left_it = 0;
while (unique_to_k.size() < k && to_left_it < to_left.size()) {
if (to_left.at(to_left_it) < to_right)
to_left_it++;
else {
unique_to_k.insert(vines.at(to_left.at(to_left_it)));
swaps += to_left.at(to_left_it) - to_right - shifts;
shifts++;
to_left_it++;
}
}
if (unique_to_k.size() == k)
std::cout << swaps;
else
std::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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | #include <iostream> #include <vector> #include <set> int main() { std::ios::sync_with_stdio(false); int n, k; std::cin >> n >> k; std::vector<int> vines; std::set<int> unique_to_k; int tmp; for (int i = 0; i < n; i++) { std::cin >> tmp; vines.push_back(tmp); } std::vector<int> to_left; int to_right = -1; int size = vines.size(); for (int i = 0; i < k; i++) { // if not found if (unique_to_k.find(vines.at(i)) == unique_to_k.end()) { unique_to_k.insert(vines.at(i)); to_left.push_back(i); } // if found else if (to_right == -1) to_right = i; } std::set<int> uniques = unique_to_k; for (int i = k; i < size; i++) { // if not found if (uniques.find(vines.at(i)) == uniques.end()) { uniques.insert(vines.at(i)); to_left.push_back(i); } // if found else if (to_right == -1) to_right = i; } int swaps = 0; int shifts = 0; int to_left_it = 0; while (unique_to_k.size() < k && to_left_it < to_left.size()) { if (to_left.at(to_left_it) < to_right) to_left_it++; else { unique_to_k.insert(vines.at(to_left.at(to_left_it))); swaps += to_left.at(to_left_it) - to_right - shifts; shifts++; to_left_it++; } } if (unique_to_k.size() == k) std::cout << swaps; else std::cout << "-1"; } |
English