#include <bits/stdc++.h> using namespace std; const int N = 1e5+5; int arr[N]; bool used[N]; int main(){ ios_base::sync_with_stdio(0); int n,k,result=0,diff=0; cin >> n >> k; for(int i=0; i<n; ++i){ cin >> arr[i]; } for(int i=0; i<n; ++i){ if(!used[arr[i]]){ used[arr[i]] = 1; ++diff; } } if(diff<k){ cout << -1; return 0; } memset(used,0x0,sizeof(used)); for(int i=0,curK=0,cntK=0; i<n&&cntK<k; ++i,++curK){ if(!used[arr[i]]){ result += curK; ++cntK; --curK; used[arr[i]]=1; }else{ } } cout << result; 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 | #include <bits/stdc++.h> using namespace std; const int N = 1e5+5; int arr[N]; bool used[N]; int main(){ ios_base::sync_with_stdio(0); int n,k,result=0,diff=0; cin >> n >> k; for(int i=0; i<n; ++i){ cin >> arr[i]; } for(int i=0; i<n; ++i){ if(!used[arr[i]]){ used[arr[i]] = 1; ++diff; } } if(diff<k){ cout << -1; return 0; } memset(used,0x0,sizeof(used)); for(int i=0,curK=0,cntK=0; i<n&&cntK<k; ++i,++curK){ if(!used[arr[i]]){ result += curK; ++cntK; --curK; used[arr[i]]=1; }else{ } } cout << result; return 0; } |