#include <iostream> #include <unordered_set> #include <queue> using namespace std; int main() { int n, k; cin >> n >> k; unordered_set<int> seen_brands; queue<int> repeating_brand_index; int moves = 0; for (int i = 0; i < n; ++i) { int brand; cin >> brand; if (seen_brands.find(brand) != seen_brands.end()) { repeating_brand_index.push(i); } else { int first_free_index; if (!repeating_brand_index.empty()) { first_free_index = repeating_brand_index.front(); repeating_brand_index.pop(); repeating_brand_index.push(i); } else { first_free_index = i; } moves += i - first_free_index; seen_brands.insert(brand); if (seen_brands.size() == k) { cout << moves << '\n'; return 0; } } } cout << -1 << '\n'; 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 | #include <iostream> #include <unordered_set> #include <queue> using namespace std; int main() { int n, k; cin >> n >> k; unordered_set<int> seen_brands; queue<int> repeating_brand_index; int moves = 0; for (int i = 0; i < n; ++i) { int brand; cin >> brand; if (seen_brands.find(brand) != seen_brands.end()) { repeating_brand_index.push(i); } else { int first_free_index; if (!repeating_brand_index.empty()) { first_free_index = repeating_brand_index.front(); repeating_brand_index.pop(); repeating_brand_index.push(i); } else { first_free_index = i; } moves += i - first_free_index; seen_brands.insert(brand); if (seen_brands.size() == k) { cout << moves << '\n'; return 0; } } } cout << -1 << '\n'; return 0; } |