#include <bits/stdc++.h> using namespace std; const int k = 5*1e5 + 5; pair <long long int,long long int> tab[k]; bool vis[k]; int main(){ long long int n, m, ans = 0, poz = 1; cin>>n>>m; for(int i=0; i<n; i++){ int a; cin>>a; tab[i] = { i , a }; } sort(tab, tab+n); vis[tab[0].second] = true; for(int i=1; i<n; i++){ if(poz == m) break; if(vis[tab[i].second])continue; else{ //cout<<tab[i].second<<' '<<poz<<" "<<tab[i].first<<"\n"; ans += tab[i].first - poz; vis[tab[i].second] = true; poz++; } } if(poz == m) cout<<ans; else cout<<"-1"; }
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 | #include <bits/stdc++.h> using namespace std; const int k = 5*1e5 + 5; pair <long long int,long long int> tab[k]; bool vis[k]; int main(){ long long int n, m, ans = 0, poz = 1; cin>>n>>m; for(int i=0; i<n; i++){ int a; cin>>a; tab[i] = { i , a }; } sort(tab, tab+n); vis[tab[0].second] = true; for(int i=1; i<n; i++){ if(poz == m) break; if(vis[tab[i].second])continue; else{ //cout<<tab[i].second<<' '<<poz<<" "<<tab[i].first<<"\n"; ans += tab[i].first - poz; vis[tab[i].second] = true; poz++; } } if(poz == m) cout<<ans; else cout<<"-1"; } |