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
#include <bits/stdc++.h>
using namespace std;
int tab[500001], ile[500001], pojedyncze[500001];
int main() {
	ios_base::sync_with_stdio(0);
	int n, k, i, j;
	long long wyn = 0;
	cin >> n >> k;
	for(i = 1; i <= k; i++) {
		cin >> tab[i];
		ile[tab[i]]++;
	}
	for(i = k + 1; i <= n; i++) {
		cin >> tab[i];
		if(ile[tab[i]] > 0) tab[i] = -1;
		if(pojedyncze[tab[i]] > 0) tab[i] = -1;
		else pojedyncze[tab[i]] = 1;
	}
	i = k; j = k + 1;
	while(j <= n && tab[j] == -1) j++;
	while(i > 0 && j <= n){		
		if(ile[tab[i]] > 1) {
			ile[tab[i]]--;
			wyn += j - i;
			j++;
		}
		i--;
		while(j <= n && tab[j] == -1) j++;
	}
	while(i > 0) {
		if(ile[tab[i]] > 1) {
			cout << -1;
			return 0;
		}
		i--;
	}
	cout << wyn;
	
	return 0;
}