#include <stdio.h> typedef unsigned int ui; size_t n, k; ui *arr; size_t *has_occured; bool *is_used; int main(void) { scanf("%lu %lu", &n, &k); arr = new ui[n]; for (size_t i=0; i<n; ++i) scanf("%u", &arr[i]); size_t too_many_cnt = 0; has_occured = new size_t[n+1]{ }; is_used = new bool[n+1]{ }; for (size_t i=0; i<k; ++i) { if (has_occured[arr[i]]) ++too_many_cnt; ++has_occured[arr[i]]; } size_t result = 0; size_t found_needed_cnt = 0; for (size_t i=k; i<n && found_needed_cnt<too_many_cnt; ++i) { if (has_occured[arr[i]] || is_used[arr[i]]) continue; is_used[arr[i]] = true; result += i-k - found_needed_cnt; ++found_needed_cnt; } if (found_needed_cnt < too_many_cnt) { printf("-1\n"); return 0; } for (size_t i=k-1; i!=-1; --i) { if (has_occured[arr[i]] <= 1) continue; // result += too_many_cnt + (k-1)-i; result += k-1+too_many_cnt - i; --has_occured[arr[i]]; --too_many_cnt; } printf("%lu\n", result); 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 | #include <stdio.h> typedef unsigned int ui; size_t n, k; ui *arr; size_t *has_occured; bool *is_used; int main(void) { scanf("%lu %lu", &n, &k); arr = new ui[n]; for (size_t i=0; i<n; ++i) scanf("%u", &arr[i]); size_t too_many_cnt = 0; has_occured = new size_t[n+1]{ }; is_used = new bool[n+1]{ }; for (size_t i=0; i<k; ++i) { if (has_occured[arr[i]]) ++too_many_cnt; ++has_occured[arr[i]]; } size_t result = 0; size_t found_needed_cnt = 0; for (size_t i=k; i<n && found_needed_cnt<too_many_cnt; ++i) { if (has_occured[arr[i]] || is_used[arr[i]]) continue; is_used[arr[i]] = true; result += i-k - found_needed_cnt; ++found_needed_cnt; } if (found_needed_cnt < too_many_cnt) { printf("-1\n"); return 0; } for (size_t i=k-1; i!=-1; --i) { if (has_occured[arr[i]] <= 1) continue; // result += too_many_cnt + (k-1)-i; result += k-1+too_many_cnt - i; --has_occured[arr[i]]; --too_many_cnt; } printf("%lu\n", result); return 0; } |