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
57
58
#include <iostream>

using namespace std;


void notPossible() {
	cout << "-1";
	exit(0);
}

int main()
{
	int n, k;
	cin >> n >> k;

	int *bottles = new int[n];
	bool *brandSeen = new bool[n];
	int brandsSeen = 0;
	long switches = 0;
	int startSearchFrom = 0;

	for (int i = 0; i < n; i++) {
		cin >> bottles[i];
		bottles[i]--;
	}

	for (int i = 0; i < n; i++) {
		if (brandsSeen == k) {
			cout << switches;
			return 0;
		}
		int brand = bottles[i];
		if (!brandSeen[brand]) {
			brandSeen[brand] = true;
			brandsSeen++;
			if (startSearchFrom <= i) {
				startSearchFrom = i + 1;
			}
		} else {
			for (int j = startSearchFrom; j <= n; j++) {
				startSearchFrom = j;
				if (startSearchFrom == n) {
					notPossible();
				}
				int furtherBottleBrand = bottles[j];
				if (!brandSeen[furtherBottleBrand]) {
					switches += (j - i);
					brandSeen[furtherBottleBrand] = true;
					brandsSeen++;
					startSearchFrom++;
					break;
				}
			}

		}
	}
	notPossible();
}