#include <iostream>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
const int MAX_SHELF_CAPACITY = 5e5;
int n, k;
int brand;
int total_brands = 0;
unsigned long long switches = 0;
// virgin = first_occurence
bool was_virgin[MAX_SHELF_CAPACITY] = {};
bool is_virgin[MAX_SHELF_CAPACITY] = {};
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> brand;
if (!was_virgin[brand]) {
total_brands++;
was_virgin[brand] = true;
is_virgin[i] = true;
}
}
// Answer is negative only if there are not enough brands to cover all positions.
if (total_brands < k) {
cout << -1;
return 0;
}
int next_position = k - 1;
for (int i = 0; i < k; i++) {
if (!is_virgin[i]) {
next_position++;
while (!is_virgin[next_position]) {
next_position++;
}
switches += (unsigned long long)next_position - i;
}
}
cout << switches;
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 53 54 55 56 | #include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); const int MAX_SHELF_CAPACITY = 5e5; int n, k; int brand; int total_brands = 0; unsigned long long switches = 0; // virgin = first_occurence bool was_virgin[MAX_SHELF_CAPACITY] = {}; bool is_virgin[MAX_SHELF_CAPACITY] = {}; cin >> n >> k; for (int i = 0; i < n; i++) { cin >> brand; if (!was_virgin[brand]) { total_brands++; was_virgin[brand] = true; is_virgin[i] = true; } } // Answer is negative only if there are not enough brands to cover all positions. if (total_brands < k) { cout << -1; return 0; } int next_position = k - 1; for (int i = 0; i < k; i++) { if (!is_virgin[i]) { next_position++; while (!is_virgin[next_position]) { next_position++; } switches += (unsigned long long)next_position - i; } } cout << switches; return 0; } |
English