#include <bits/stdc++.h> using namespace std; int main() { std::ios_base::sync_with_stdio(false); long long n, k; cin >> n >> k; vector<bool> alreadyWas; for(int i = 0; i <= n; i++) alreadyWas.push_back(false); long long Pk; int howManyDifferent = 0; long long timeNeeded; long long sumOfWrongBottles = 0; for(int i = 0; i < n; i++) { int nextBottle; cin >> nextBottle; if(alreadyWas[nextBottle]) { sumOfWrongBottles += i; } else { alreadyWas[nextBottle] = true; howManyDifferent++; if(howManyDifferent == k){ Pk = i; break; } } } if(howManyDifferent == k) { timeNeeded = (k + Pk)*(Pk - k + 1)/2 - sumOfWrongBottles; cout << timeNeeded; } else { cout << -1; } 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 | #include <bits/stdc++.h> using namespace std; int main() { std::ios_base::sync_with_stdio(false); long long n, k; cin >> n >> k; vector<bool> alreadyWas; for(int i = 0; i <= n; i++) alreadyWas.push_back(false); long long Pk; int howManyDifferent = 0; long long timeNeeded; long long sumOfWrongBottles = 0; for(int i = 0; i < n; i++) { int nextBottle; cin >> nextBottle; if(alreadyWas[nextBottle]) { sumOfWrongBottles += i; } else { alreadyWas[nextBottle] = true; howManyDifferent++; if(howManyDifferent == k){ Pk = i; break; } } } if(howManyDifferent == k) { timeNeeded = (k + Pk)*(Pk - k + 1)/2 - sumOfWrongBottles; cout << timeNeeded; } else { cout << -1; } return 0; } |