#include <iostream> #include <vector> #include <set> #include <map> using namespace std; typedef vector<int> vint; typedef set<int> sint; typedef map<int, int> mint; typedef long long ll; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; vint a; int ai; for (int i = 0; i < n; i++) { cin >> ai; a.push_back(ai); } vint to_change; mint k_map, seen; sint a_set; ll sum = 0, last = -1; bool skip = false; for (int i = 0; i < n; i++) { if (!skip) { if (i < k) k_map[a[i]] = true; if (i >= k && k_map[a[i]] != true) { if (to_change.size() == 0) skip = true; sum += i - to_change.back(); to_change.pop_back(); k_map[a[i]] = true; } if (i < k && seen[a[i]] == true) { to_change.push_back(i); } else seen[a[i]] = true; last = a[i]; } a_set.insert(a[i]); } if (a_set.size() < k) cout << -1; else cout << sum; 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 | #include <iostream> #include <vector> #include <set> #include <map> using namespace std; typedef vector<int> vint; typedef set<int> sint; typedef map<int, int> mint; typedef long long ll; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; vint a; int ai; for (int i = 0; i < n; i++) { cin >> ai; a.push_back(ai); } vint to_change; mint k_map, seen; sint a_set; ll sum = 0, last = -1; bool skip = false; for (int i = 0; i < n; i++) { if (!skip) { if (i < k) k_map[a[i]] = true; if (i >= k && k_map[a[i]] != true) { if (to_change.size() == 0) skip = true; sum += i - to_change.back(); to_change.pop_back(); k_map[a[i]] = true; } if (i < k && seen[a[i]] == true) { to_change.push_back(i); } else seen[a[i]] = true; last = a[i]; } a_set.insert(a[i]); } if (a_set.size() < k) cout << -1; else cout << sum; return 0; } |