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 <map>
using namespace std;

const int N = 500003;
int n, k, arr[N], toChange, moved, useless;
long long score;
map <int, int> M;

int main() {
	ios_base::sync_with_stdio(0);
	cin >> n >> k;
	for (int i = 1; i <= n; i++) {
		cin >> arr[i];
		if (i <= k) {
			if (M[arr[i]])
				score += k + 1 - i + toChange++;
			M[arr[i]]++;
		}
		else {
			bool g = 0;
			if (!M[arr[i]] && moved < toChange && useless) {
				score += useless;
				g = 1;
			}
			if (M[arr[i]] && g==0) 
				useless++;
			else 
				moved++;
			M[arr[i]]++;
		}
	}
	if (moved < toChange) cout << -1;
	else cout<< score;
}