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
#include <iostream>
#include <vector>
using namespace std;
int main()
{
	int n, k;
	cin >> n >> k;
	vector<int> A(n);
	for (int &a: A) cin >> a;

	vector<int> B(n);
	vector<int> C(n);
	int n_to_remove = 0;
	int n_to_add = 0;
	int i;
	long long count=0;
	for (i=0; i<k; i++) {
		if (B[A[i]-1]++ > 0) {
			count += k-1-i;
			n_to_remove++;
		}
	}
	for (; n_to_remove > n_to_add && i<n; i++) {
		if (B[A[i]-1] > 0) continue;
		if (C[A[i]-1]++ == 0) {
			count += i-k+1;
			n_to_add++;
		}
	}
	if (n_to_remove != n_to_add) {
		count = -1;
	}
	cout << count << "\n";
	return 0;
}