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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <cmath>

using namespace std;

int an[500003];
int sort[500003];
bool roz[500003];

int main(){
	int k,n,j,countnext=0;
	long long t=0;
	cin >>n>>k;
	int w;
	for(w=1;w<=n;w++){
		cin >> j;
		an[w]=j;
		sort[j]++;
		if(sort[j]==1)roz[w]=true;
	}
	roz[n+1]=true;
	for(w=1;w<=n+1;w++){
		//cout << roz[w];
		
	}
	int countbefore =k;
	for(int i=k;i>=0;i--){
		if(roz[i] ==false) {
			countbefore =i;
			break;
		}
	}
	if(countbefore <=1) {
		cout <<0<<endl;
		return 0;
	}
	//cout <<countbefore;
	//countnext =k+1;
	for(int i=k+1;i<=n+1;i++){
		if(roz[i] ==true) {
			countnext =i;
			break;
		}
	}
	if(countnext >n) {
			cout <<-1<<endl;
			return 0;
		}
	//cout<<countnext;
	for(int j=n+1;j>=1;j--){
		t+=k-countbefore +countnext-k;
		for(int i=countbefore-1;i>=0;i--){
			if(roz[i] ==false) {
				countbefore =i;
				break;
			}
		}
		if(countbefore <=1) {
			cout <<t <<endl;
			return 0;
		}

		for(int i=countnext+1;i<=n+1;i++){
			if(roz[i] ==true) {
				countnext =i;
				break;
			}
		}
		if(countnext >n) {
			cout <<-1<<endl;
			return 0;
		}
		
		

		
	}
		

	

    return 0;
}