#include <iostream> #include <vector> #include <map> using namespace std; int getNearest(map<int, int> *m) { int lowestkey = (*m).begin()->first; int lowest = (*m).begin()->second; for(map<int, int>::iterator it = (*m).begin(); it != (*m).end(); ++it) { int x = it->second; if(x < lowest) { lowest = x; lowestkey = it->first; } } (*m).erase(lowestkey); return lowest; } int main() { int n, k; cin >> n >> k; vector<int> data; map<int, int> type_map; for(int i = 0; i < n; i++) { int x; cin >> x; data.push_back(x); if(type_map.count(x) == 0) type_map[x] = i; } if(type_map.size() < k) { cout << -1; return 0; } int count = 0; for(int i = 0; i < k; i++) { for(int j = getNearest(&type_map); j > i; j--) { int x = data[j]; data[j] = data[j-1]; data[j-1] = x; count++; } } cout << count; 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 | #include <iostream> #include <vector> #include <map> using namespace std; int getNearest(map<int, int> *m) { int lowestkey = (*m).begin()->first; int lowest = (*m).begin()->second; for(map<int, int>::iterator it = (*m).begin(); it != (*m).end(); ++it) { int x = it->second; if(x < lowest) { lowest = x; lowestkey = it->first; } } (*m).erase(lowestkey); return lowest; } int main() { int n, k; cin >> n >> k; vector<int> data; map<int, int> type_map; for(int i = 0; i < n; i++) { int x; cin >> x; data.push_back(x); if(type_map.count(x) == 0) type_map[x] = i; } if(type_map.size() < k) { cout << -1; return 0; } int count = 0; for(int i = 0; i < k; i++) { for(int j = getNearest(&type_map); j > i; j--) { int x = data[j]; data[j] = data[j-1]; data[j-1] = x; count++; } } cout << count; return 0; } |