#include <iostream> #include<map> #include<vector> #include<algorithm> using namespace std; int n, k, d; map<int, int> pos; vector<int> v; int main() { ios::sync_with_stdio(false); cin >> n >> k; for(int i = 0; i < n; i++) { cin >> d; if(pos.find(d) == pos.end()) { pos[d] = i; } else { pos[d] = min(pos[d], i); } } if (pos.size() < k) { cout << -1; return 0; } map<int, int>::iterator it; for (it = pos.begin(); it != pos.end(); it++) { v.push_back(it->second); } sort(v.begin(), v.end()); long long tmp = 0L; for(int i=0; i<k; i++) { tmp += (long long)(v[i] - i); } cout << tmp; 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<map> #include<vector> #include<algorithm> using namespace std; int n, k, d; map<int, int> pos; vector<int> v; int main() { ios::sync_with_stdio(false); cin >> n >> k; for(int i = 0; i < n; i++) { cin >> d; if(pos.find(d) == pos.end()) { pos[d] = i; } else { pos[d] = min(pos[d], i); } } if (pos.size() < k) { cout << -1; return 0; } map<int, int>::iterator it; for (it = pos.begin(); it != pos.end(); it++) { v.push_back(it->second); } sort(v.begin(), v.end()); long long tmp = 0L; for(int i=0; i<k; i++) { tmp += (long long)(v[i] - i); } cout << tmp; return 0; } |