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

using namespace std;

typedef long long LL;

const int MAXN = 5*100000 + 1;

int n, k;
int a[MAXN];

int main() {
    scanf("%d %d", &n, &k);
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);

    int size = 0;
    int last = -1;
    set<int> s;
    vector<int> dup;
    
    for(int i = 0; i < n && size < k; i++) {
        if(s.find(a[i]) == s.end()) {
            size++;
            s.insert(a[i]);
        } else {
            dup.push_back(i);
        }
        last = i;
    }

    if(size < k) {
        printf("-1\n");
        return 0;
    } 

    LL res = 0;
    for(auto it = dup.rbegin(); it != dup.rend(); it++) {
        res += (last - *it);
        last--;
    }
    printf("%lld\n", res);
}