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
53
54
55
56
#include<bits/stdc++.h>
using namespace std;

bool gaming(const pair<int, int>& a, const pair<int, int>& b)
{
	if(a.second != b.second) return a.second < b.second;
	return a.first < b.first;
}

int main()
{
	int n, k;
	cin >> n >> k;
	vector<pair<int, int>> elements;
	elements.reserve(n);
	for(int i = 0; i < n; ++i)
	{
		int t;
		cin >> t;
		elements.push_back({t, i});
	}
	sort(elements.begin(), elements.end());
	int current_index = 0;
	for(int i = 1; i < elements.size(); ++i)
	{
		if(elements[current_index].first == elements[i].first)
		{
		}
		else
		{
			elements[++current_index] = elements[i];
		}
	}
	++current_index;
	elements.resize(current_index);
	sort(elements.begin(), elements.end(), gaming);
	/*for(auto [val, pos] : elements)
	{
		cout << val << ' ' << pos << '\n';
	}*/
	if(elements.size() < k)
	{
		cout << -1;
		return 0;
	}
	else
	{
		int64_t wynik = 0;
		for(int i = 0; i < k; ++i)
		{
			wynik += elements[i].second - i;
		}
		cout << wynik;
		return 0;
	}
}