#include <cstdio> #include <vector> #include <list> using namespace std; int main() { int n,k, moves = 0; scanf("%d %d", &n, &k); vector<int> c(n,0); list<int> stack; if (k == 1) { printf("0\n"); return 0; } for (int i = 0; i < n; ++i) { int b; scanf("%d", &b); if (i < k) { if (c[b-1] == 1) { stack.push_back(i); } c[b-1] = 1; } else { if (c[b-1] == 0 && !stack.empty()) { int f = stack.front(); stack.pop_front(); moves += (i-f); c[b-1] = 1; } if (stack.empty()) { break; } } } if (!stack.empty()) { printf("%d\n", -1); } else { printf("%d\n", moves); } 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 | #include <cstdio> #include <vector> #include <list> using namespace std; int main() { int n,k, moves = 0; scanf("%d %d", &n, &k); vector<int> c(n,0); list<int> stack; if (k == 1) { printf("0\n"); return 0; } for (int i = 0; i < n; ++i) { int b; scanf("%d", &b); if (i < k) { if (c[b-1] == 1) { stack.push_back(i); } c[b-1] = 1; } else { if (c[b-1] == 0 && !stack.empty()) { int f = stack.front(); stack.pop_front(); moves += (i-f); c[b-1] = 1; } if (stack.empty()) { break; } } } if (!stack.empty()) { printf("%d\n", -1); } else { printf("%d\n", moves); } return 0; } |