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
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define endl "\n"
using namespace std;
int n, k;
int e;
vector<int> v;
set<int> ch;
bool c[500005];
ll w;
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> k;
    for (int i = 0; i < n; i++){
        int a;
        cin >> a;
        v.pb(a);
        ch.insert(a);
    }
    if (ch.size() < k){
        cout << -1;
        exit(0);

    }
    e = 0;
    for (int I = 0; I < k; I++){
        int i = v[I];
        if (c[i]){
            for (int J = max(I, e) + 1; J < n; J++){
                int j = v[J];
                if (!c[j]){
                        w += J - I;
                        c[j] = true;
                        e = J;
                        break;
                }
            }
        }
        else c[i] = true;
    }
    cout << w;
}