#include <bits/stdc++.h> using namespace std; long long n, k, mov, a, b; int t[500007]; int cnt[500007]; vector <int> same; vector <int> diff; long long res; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> k; for(int i = 1; i <= n; i++){ cin >> t[i]; cnt[t[i]]++; if(cnt[t[i]] > 1 && i <= k){ same.push_back(i); } else if(i > k && cnt[t[i]] == 1){ diff.push_back(i); } } if(same.size() > diff.size()){ cout << -1; return 0; } for(int i = 0; i < same.size(); i++){ //cout << same[i] << "i=" << i << ' '; //cout << diff[i] << "i=" << i << '\n'; a = same[i] + mov; b = diff[i]; mov++; res += b - a; } for(int i = same.size() - 1; i >= 0; i--){ a = same[i] + mov; res += k + i + 1 - a; mov--; } cout << res; 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 50 51 52 | #include <bits/stdc++.h> using namespace std; long long n, k, mov, a, b; int t[500007]; int cnt[500007]; vector <int> same; vector <int> diff; long long res; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> k; for(int i = 1; i <= n; i++){ cin >> t[i]; cnt[t[i]]++; if(cnt[t[i]] > 1 && i <= k){ same.push_back(i); } else if(i > k && cnt[t[i]] == 1){ diff.push_back(i); } } if(same.size() > diff.size()){ cout << -1; return 0; } for(int i = 0; i < same.size(); i++){ //cout << same[i] << "i=" << i << ' '; //cout << diff[i] << "i=" << i << '\n'; a = same[i] + mov; b = diff[i]; mov++; res += b - a; } for(int i = same.size() - 1; i >= 0; i--){ a = same[i] + mov; res += k + i + 1 - a; mov--; } cout << res; return 0; } |