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
#include<cstdio>
#include<vector>
#include<algorithm>

using namespace std;

#define MAXN 100000


int seen[MAXN];

int main()
{
	int n;
	int k;
	vector<int> v;
	scanf("%d%d", &n, &k);
	for (int i = 0; i < n; i++) {
		int value = 0;
		scanf("%d", &value);
		v.push_back(value);
	}
	
	vector<int> repeated_position;
	vector<int> nearest_missing_position;
	
	for (int i = 0; i < k; ++i) {
		if (seen[v[i]] == 0) {
			seen[v[i]] = 1;
		} else {
			repeated_position.push_back(i);
		}
	}
	
	for (int i = k; i < n; ++i) {
		if (seen[v[i]] == 0) {
			seen[v[i]] = 1;
			nearest_missing_position.push_back(i);
		}
	}
	
	if (repeated_position.size() > nearest_missing_position.size()) {
		printf("-1\n");
	} else {
		long long distance_sum = 0;
		for (int i = 0; i < repeated_position.size(); i++) {
			distance_sum += nearest_missing_position[i] - repeated_position[i];
		}
		printf("%lld\n", distance_sum);
	}
	
}