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
//#include <unordered_set>
#include <vector>
#include <cstdio>

int main() {

    int n, k;
    unsigned long long count = 0LL;

    scanf("%d %d", &n, &k);

    //std::unordered_set<int> hash;
    //hash.reserve(k);
    std::vector<bool> hash(n+1, false);

    std::vector<int> duplicated;
    for (int i = 0; i < n; ++i) {
        int t;
        scanf("%d", &t);
        if (hash[t]) {
            if (i < k) 
                duplicated.push_back(i);
        } else {
            if (i >= k && !duplicated.empty()) {
                count += (unsigned long long)(i - duplicated.back());
                duplicated.pop_back();
            }

            if (i >= k-1 && duplicated.empty()) {
                break; // the end
            }

            if (duplicated.size() > n-k) {
                break;
            }

            hash[t] = true;
        }
    }
    

    if (duplicated.empty())
        printf("%llu\n", count);
    else
        printf("-1\n");

    return 0;
}