#include <string> #include <iostream> #include <algorithm> using namespace std; int main(int argc, char const *argv[]) { int n, k; int arr[500001]; int pos[500001]; cin >> n >> k; long long result = 0; for (int i = 0; i < n; i++) { pos[i] = -1; cin >> arr[i]; } pos[n] = -1; for (int i = k - 1; i >= 0; i--) { if (pos[arr[i]] == -1) { pos[arr[i]] = i; } else { while (k < n && pos[arr[k]] != -1) { k++; } if (k == n) { cout <<-1 << endl; return 0; } result += k - pos[arr[i]]; pos[arr[k]] = pos[arr[i]]; pos[arr[i]] = i; } } cout << result << endl; 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 | #include <string> #include <iostream> #include <algorithm> using namespace std; int main(int argc, char const *argv[]) { int n, k; int arr[500001]; int pos[500001]; cin >> n >> k; long long result = 0; for (int i = 0; i < n; i++) { pos[i] = -1; cin >> arr[i]; } pos[n] = -1; for (int i = k - 1; i >= 0; i--) { if (pos[arr[i]] == -1) { pos[arr[i]] = i; } else { while (k < n && pos[arr[k]] != -1) { k++; } if (k == n) { cout <<-1 << endl; return 0; } result += k - pos[arr[i]]; pos[arr[k]] = pos[arr[i]]; pos[arr[i]] = i; } } cout << result << endl; return 0; } |