#include <bits/stdc++.h> using namespace std; #define LL long long // TODO: Nie wczytuj wszystkich liczb LL solve(vector<int> &a, int k) { int n = a.size(); LL moves = 0; vector<bool> seen(a.size()+2, false); int left = 0,right = 1; while (left < k && right < n) { //printf("Processing left elem a[%d]=%d\n", left, a[left]); if (!seen[a[left]]) { seen[a[left]] = true; left++; } else { while (right < n && seen[a[right]]) { right++; } if (right == n) break; seen[a[right]] = true; moves += right - left; swap(a[left], a[right]); left++; } } if (right == n) return -1; return moves; } int main() { int n,k; scanf("%d%d", &n,&k); vector<int> a(n, 0); for (int i=0; i < n; i++) { scanf("%d", &a[i]); } printf("%lld\n", solve(a,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 | #include <bits/stdc++.h> using namespace std; #define LL long long // TODO: Nie wczytuj wszystkich liczb LL solve(vector<int> &a, int k) { int n = a.size(); LL moves = 0; vector<bool> seen(a.size()+2, false); int left = 0,right = 1; while (left < k && right < n) { //printf("Processing left elem a[%d]=%d\n", left, a[left]); if (!seen[a[left]]) { seen[a[left]] = true; left++; } else { while (right < n && seen[a[right]]) { right++; } if (right == n) break; seen[a[right]] = true; moves += right - left; swap(a[left], a[right]); left++; } } if (right == n) return -1; return moves; } int main() { int n,k; scanf("%d%d", &n,&k); vector<int> a(n, 0); for (int i=0; i < n; i++) { scanf("%d", &a[i]); } printf("%lld\n", solve(a,k)); } |