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
#include <bits/stdc++.h>
using namespace std;
#define TESTS 0


const int N = 500100;

int n, k, a[N], cnt[N];

void solve() {
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    vector<int> poses;
    long long ans = 0;
    for (int i = 1; i <= k; i++) {
        if (cnt[a[i]]) {
            poses.push_back(i);
        }
        else
            cnt[a[i]] = 1;
    }
    reverse(poses.begin(), poses.end());
    for (int i = k+1; i <= n; i++) {
        if (poses.empty())
            break;
        if (cnt[a[i]] == 0) {
            cnt[a[i]] = 1;
            ans += i-poses.back();
            poses.pop_back();
        }
    }
    if (!poses.empty())
        cout << -1 << "\n";
    else
        cout << ans << "\n";
}



int main() {
    int tt = 1; 
#if TESTS
    cin >> tt;
#endif
    while(tt--) {
        solve();
    }
}