#include<bits/stdc++.h> #define ST first #define ND second #define ll long long #define ld long double #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " using namespace std; const ll INF = 1e9 + 9; const ll MOD = 1e9 + 7; const long long LINF = (ll)1e18 + 3; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n,k; cin >> n >> k; vector<int> cnt(n+1), tab(n+1); int different = 0, endInd = -1; for(int i = 0; i < n; i++){ cin >> tab[i]; if(cnt[tab[i]] == 0) different++; cnt[tab[i]]++; if(different == k){ endInd = i; break; } } if(endInd == -1){ cout << -1 << "\n"; return 0; } ll ans = 0; int subtract = 0; for(int i = endInd; i >= 0; i--){ if(cnt[tab[i]] > 1){ ans += (ll)(endInd - subtract - i); subtract++; cnt[tab[i]]--; } } cout << ans << "\n"; 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 | #include<bits/stdc++.h> #define ST first #define ND second #define ll long long #define ld long double #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " using namespace std; const ll INF = 1e9 + 9; const ll MOD = 1e9 + 7; const long long LINF = (ll)1e18 + 3; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n,k; cin >> n >> k; vector<int> cnt(n+1), tab(n+1); int different = 0, endInd = -1; for(int i = 0; i < n; i++){ cin >> tab[i]; if(cnt[tab[i]] == 0) different++; cnt[tab[i]]++; if(different == k){ endInd = i; break; } } if(endInd == -1){ cout << -1 << "\n"; return 0; } ll ans = 0; int subtract = 0; for(int i = endInd; i >= 0; i--){ if(cnt[tab[i]] > 1){ ans += (ll)(endInd - subtract - i); subtract++; cnt[tab[i]]--; } } cout << ans << "\n"; return 0; } |