#include <iostream> #include <map> using namespace std; bool IsUsed(int* used, int num, int k) { for (int i = 0; i < k; i++) { if (used[i] == num) return true; } return false; } int FindFirstDifferent(int* a, int num, int n) { for (int i = 0; i < n; i++) { if (a[i] != num) return i; } return 0; //Nic nie znaleziono } int main() { int n, k; cin >> n >> k; int a[n]; int used[k]; int used_index = 0, to_change_index = 1; int seconds = 0; map<int, int> bottles; for (int i = 0; i < n; i++) { cin >> a[i]; bottles[a[i]]++; } if (bottles.size() < k) { cout << -1; return 0; } used[used_index] = a[0]; used_index++; for (int i = 1; i < n; i++) { if (a[0] != a[i] && i < k) { used[used_index] = a[i]; to_change_index++; used_index++; } else if (a[0] != a[i] && i >= k) { if(!IsUsed(used, a[i], k)) { for (int j = i; j > to_change_index; j--) { swap(a[j], a[j - 1]); seconds++; } used[used_index] = a[to_change_index]; used_index++; to_change_index++; } } else { int index = i + FindFirstDifferent(&a[i], a[i], n - i + 1); swap(a[i], a[index]); seconds += index - i; i--; } if (to_change_index >= k) break; } cout << seconds; 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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | #include <iostream> #include <map> using namespace std; bool IsUsed(int* used, int num, int k) { for (int i = 0; i < k; i++) { if (used[i] == num) return true; } return false; } int FindFirstDifferent(int* a, int num, int n) { for (int i = 0; i < n; i++) { if (a[i] != num) return i; } return 0; //Nic nie znaleziono } int main() { int n, k; cin >> n >> k; int a[n]; int used[k]; int used_index = 0, to_change_index = 1; int seconds = 0; map<int, int> bottles; for (int i = 0; i < n; i++) { cin >> a[i]; bottles[a[i]]++; } if (bottles.size() < k) { cout << -1; return 0; } used[used_index] = a[0]; used_index++; for (int i = 1; i < n; i++) { if (a[0] != a[i] && i < k) { used[used_index] = a[i]; to_change_index++; used_index++; } else if (a[0] != a[i] && i >= k) { if(!IsUsed(used, a[i], k)) { for (int j = i; j > to_change_index; j--) { swap(a[j], a[j - 1]); seconds++; } used[used_index] = a[to_change_index]; used_index++; to_change_index++; } } else { int index = i + FindFirstDifferent(&a[i], a[i], n - i + 1); swap(a[i], a[index]); seconds += index - i; i--; } if (to_change_index >= k) break; } cout << seconds; return 0; } |