#include <bits/stdc++.h> #define ll long long #define newl cout << "\n" #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) using namespace std; const int iinf = (int) 1e9 + 111; const long long inf = (long long) 1e18 + iinf; const int N = 1e6 + 111; #define list sdkfndsf int32_t main(){ int n, k; cin >> n >> k; vector<int> v(n); vector<int> mp(n + 1, 0); vector<int> mp1(n + 1, 0); for(int &it : v){ cin >> it; } for(int i = 0; i < k; i++){ mp[v[i]]++; } for(int i = k; i < n; i++){ mp1[v[i]]++; } queue<int> list; for(int i = k; i < n; i++){ if (mp1[v[i]] != -1 && !mp[v[i]]){ list.emplace(i); mp1[v[i]] = -1; } } int ans = 0; for(int i = k - 1; i >= 0; i--){ if (mp[v[i]] == 1) continue; if (list.empty()){ ans = -1; break; } int ind = list.front(); list.pop(); ans+= ind - i; mp[v[i]]--; } cout << ans; 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 | #include <bits/stdc++.h> #define ll long long #define newl cout << "\n" #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) using namespace std; const int iinf = (int) 1e9 + 111; const long long inf = (long long) 1e18 + iinf; const int N = 1e6 + 111; #define list sdkfndsf int32_t main(){ int n, k; cin >> n >> k; vector<int> v(n); vector<int> mp(n + 1, 0); vector<int> mp1(n + 1, 0); for(int &it : v){ cin >> it; } for(int i = 0; i < k; i++){ mp[v[i]]++; } for(int i = k; i < n; i++){ mp1[v[i]]++; } queue<int> list; for(int i = k; i < n; i++){ if (mp1[v[i]] != -1 && !mp[v[i]]){ list.emplace(i); mp1[v[i]] = -1; } } int ans = 0; for(int i = k - 1; i >= 0; i--){ if (mp[v[i]] == 1) continue; if (list.empty()){ ans = -1; break; } int ind = list.front(); list.pop(); ans+= ind - i; mp[v[i]]--; } cout << ans; return 0; } |