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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<long long> arr;
vector<long long> brands;
long long sum = 0;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

	long long n, k;
	cin >> n >> k;

	long long t;
	for (long long i = 0; i < n; i++) {
		cin >> t;
		arr.push_back(t);
	}

	for (long long i = 0; i < n; i++) { // count brands
		if (!binary_search(brands.begin(), brands.end(), arr[i])) {
			brands.insert(lower_bound(brands.begin(), brands.end(), arr[i]), arr[i]);
		}
	}
	
	if (k > brands.size()) { // if less brands than expected print -1
		cout << "-1";
		return 0;
	}

	brands.erase(lower_bound(brands.begin(), brands.end(), arr[0]));
	long long locked = 1;
	for (long long i = 1; i < n && locked < k; i++) { // take first element of each brand and put it at the front
		if (binary_search(brands.begin(), brands.end(), arr[i])) { // if no elements of this brand are locked -> lock this one
			sum += i - locked;
			brands.erase(lower_bound(brands.begin(), brands.end(), arr[i]));
			locked++;
		}
	}
	cout << sum;
}