#include <bits/stdc++.h> using namespace std; using ll = long long; unordered_map<int, int> idx{}; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n{}, k{}; cin >> n >> k; int x{}; for (int i = 0; i < n; i++) { cin >> x; if (idx.find(x) == idx.end()) idx[x] = i; } vector<int> a{}; for (auto p : idx) a.push_back(p.second); if (a.size() < k) { cout << "-1\n"; return 0; } sort(a.begin(), a.end()); ll ans{}; for (int i = 0; i < k; i++) ans += a[i]-i; cout << ans << "\n"; }
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 | #include <bits/stdc++.h> using namespace std; using ll = long long; unordered_map<int, int> idx{}; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n{}, k{}; cin >> n >> k; int x{}; for (int i = 0; i < n; i++) { cin >> x; if (idx.find(x) == idx.end()) idx[x] = i; } vector<int> a{}; for (auto p : idx) a.push_back(p.second); if (a.size() < k) { cout << "-1\n"; return 0; } sort(a.begin(), a.end()); ll ans{}; for (int i = 0; i < k; i++) ans += a[i]-i; cout << ans << "\n"; } |