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
#include <iostream>

using namespace std;

const int SIZE = 500001;

int n, k, l, r, b;
long long cost;
bool used[SIZE],
     fresh[SIZE];

int main() {
    cin >> n >> k;
    for(int i = 0; i < n; i++) {
        cin >> b;
        if(!used[b]) {
            fresh[i] = true;
            used[b] = true;
        }
    }

    while(l < n && fresh[l])
        l++;
    r = l + 1;

    while(l < k) {
        while(!fresh[r] && r < n)
            r++;
        if(r == n) {
            cost = -1;
            break;
        }

        cost += r - l;
        l++; r++;
    }

    cout << cost << "\n";
}