#include <iostream>
#include <stack>
#include <unordered_map>
std::unordered_map<int, bool> map;
std::stack<int> pary;
int value = 0;
int main()
{
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
int n, k;
std::cin >> n >> k;
for (int i = 0; i < n; i++) {
int to_map;
std::cin >> to_map;
if (i < k) {
if(!map.count(to_map)) {
map[to_map] = true;
}
else {
pary.push(i);
}
}
else {
if (pary.size() == 0) {
break;
}
if (!map.count(to_map)) {
int nr_of_element = pary.top();
pary.pop();
value += i - nr_of_element;
map[to_map] = true;
}
}
}
if (pary.empty()) {
std::cout << value << std::endl;
}
else {
std::cout << "-1" << std::endl;
}
}
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 | #include <iostream> #include <stack> #include <unordered_map> std::unordered_map<int, bool> map; std::stack<int> pary; int value = 0; int main() { std::ios_base::sync_with_stdio(0); std::cin.tie(0); int n, k; std::cin >> n >> k; for (int i = 0; i < n; i++) { int to_map; std::cin >> to_map; if (i < k) { if(!map.count(to_map)) { map[to_map] = true; } else { pary.push(i); } } else { if (pary.size() == 0) { break; } if (!map.count(to_map)) { int nr_of_element = pary.top(); pary.pop(); value += i - nr_of_element; map[to_map] = true; } } } if (pary.empty()) { std::cout << value << std::endl; } else { std::cout << "-1" << std::endl; } } |
English