#include <iostream> using namespace std; bool checkIfPossible(int* arr, int n, int k) { int count = 0; for (int i = 0; i < n; i++) { if (arr[i]) { count++; } } if (count >= k) { return true; } else { return false; } } int solution(int n, int k) { if (k == 1) { return 0; } int* arr = new int[n]; int* occur = new int[n]; for (int i = 0; i < n; i++) { occur[i] = 0; } int num; for (int i = 0; i < n; i++) { cin >> num; arr[i] = num; occur[num - 1] = 1; } if (checkIfPossible(occur, n, k)) { int sec = 0; int* occur_left = new int[n]; for (int i = 0; i < n; i++) { occur_left[i] = 0; } occur_left[arr[0] - 1] = 1; int pos_left = 2; for (int i = 1; i < k; i++) { if (occur_left[arr[i] - 1]) { for (int j = pos_left; j < n; j++) { if (!occur_left[arr[j] - 1]) { sec += (j - i); pos_left = j + 1; occur_left[arr[j] - 1] = 1; break; } } } } return sec; } else { return -1; } } int main() { int n, k; cin >> n >> k; cout << solution(n, k); }
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 | #include <iostream> using namespace std; bool checkIfPossible(int* arr, int n, int k) { int count = 0; for (int i = 0; i < n; i++) { if (arr[i]) { count++; } } if (count >= k) { return true; } else { return false; } } int solution(int n, int k) { if (k == 1) { return 0; } int* arr = new int[n]; int* occur = new int[n]; for (int i = 0; i < n; i++) { occur[i] = 0; } int num; for (int i = 0; i < n; i++) { cin >> num; arr[i] = num; occur[num - 1] = 1; } if (checkIfPossible(occur, n, k)) { int sec = 0; int* occur_left = new int[n]; for (int i = 0; i < n; i++) { occur_left[i] = 0; } occur_left[arr[0] - 1] = 1; int pos_left = 2; for (int i = 1; i < k; i++) { if (occur_left[arr[i] - 1]) { for (int j = pos_left; j < n; j++) { if (!occur_left[arr[j] - 1]) { sec += (j - i); pos_left = j + 1; occur_left[arr[j] - 1] = 1; break; } } } } return sec; } else { return -1; } } int main() { int n, k; cin >> n >> k; cout << solution(n, k); } |