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
59
60
61
#include <set>
#include <stdio.h>
#include <vector>

int main()
{
	int n, k, bottle;
	scanf("%d %d", &n, &k);

	std::vector<int> bottles;
	std::set<int> uniqueBottles;
	for (int i = 0; i < n; ++i)
	{
		scanf("%d", &bottle);
		bottles.push_back(bottle);
		uniqueBottles.insert(bottle);
	}

	if (static_cast<int>(uniqueBottles.size()) < k)
	{
		printf("-1\n");
	}
	else
	{
		std::vector<int> bottlesToRemove;
		std::vector<int> bottlesToUse;
		std::set<int> usedBottles;
		for (int i = 0; i < n; ++i)
		{
			const auto bottle = bottles[i];
			if (i < k)
			{
				if (usedBottles.count(bottle))
				{
					bottlesToRemove.push_back(i);
				}
				else
				{
					usedBottles.insert(bottle);
				}
			}
			else if (!usedBottles.count(bottle))
			{
				bottlesToUse.push_back(i);
				usedBottles.insert(bottle);
				if (bottlesToUse.size() == bottlesToRemove.size())
				{
					break;
				}
			}
		}

		int moves{0};
		for (int i = static_cast<int>(bottlesToRemove.size()) - 1; i >= 0; --i)
		{
			moves += bottlesToUse[i] - bottlesToRemove[i];
		}
		printf("%d\n", moves);
	}
	return 0;
}