#include <bits/stdc++.h> using namespace std; #define fo(i, n) for(int i=0; i<n; i++) #define FO(i, k, n) for(int i=k;i<n;i++) #define chck(x) cout<<#x<<" "<<x<<"\n"; template<typename... T> void read(T&... args){ ((cin >> args), ...); } const int MAX = 5e5+7; int in[MAX]; bool seen[MAX]; queue<int>ebebe; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k; cin >> n >> k; int i = 1, w = 0, kc = k; FO(i, 1, n+1) cin >> in[i]; while(k && i <= n){ if(!seen[in[i]]){ seen[in[i]] = true; k--; if(!ebebe.empty() && i > kc){ w += i - ebebe.front(); ebebe.pop(); } } else{ ebebe.push(i); } i++; } cout << (k ? -1 : w) << "\n"; }
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 | #include <bits/stdc++.h> using namespace std; #define fo(i, n) for(int i=0; i<n; i++) #define FO(i, k, n) for(int i=k;i<n;i++) #define chck(x) cout<<#x<<" "<<x<<"\n"; template<typename... T> void read(T&... args){ ((cin >> args), ...); } const int MAX = 5e5+7; int in[MAX]; bool seen[MAX]; queue<int>ebebe; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k; cin >> n >> k; int i = 1, w = 0, kc = k; FO(i, 1, n+1) cin >> in[i]; while(k && i <= n){ if(!seen[in[i]]){ seen[in[i]] = true; k--; if(!ebebe.empty() && i > kc){ w += i - ebebe.front(); ebebe.pop(); } } else{ ebebe.push(i); } i++; } cout << (k ? -1 : w) << "\n"; } |