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
#include<iostream>
#include<vector>
#include<unordered_set>

#define SZ(x) int(x.size())

using namespace std;

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

	int n, k; cin >> n >> k;
	vector<int> a(n);
	for (int i = 0; i < n; i++)
		cin >> a[i];
		
	unordered_set<int> taken;
	long long sum_left = 0;
	for (int i = 0; i < k; i++) {
		if (taken.find(a[i]) == taken.end()) 
			taken.insert(a[i]);
		else
			sum_left += i;
	}

	long long sum_right = 0;
	for (int i = k; i < n and SZ(taken) < k; i++) 
		if (taken.find(a[i]) == taken.end()) {
			taken.insert(a[i]);
			sum_right += i;
		}

	if (SZ(taken) == k)
		cout << sum_right - sum_left << "\n";
	else
		cout << "-1\n";
}