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
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
using namespace std;

void debug(){cerr<<"\n";}
template <typename H, typename... T>
void debug(H h, T... t) {cerr<<h; if (sizeof...(t)) cerr << ", "; debug(t...);}
#define deb(x) cerr<<#x<<" = ";debug(x);

const int mxn = 5e5 + 10;
 
void solve()
{
    int n,k;
    cin >> n >> k;
    vector <bool> vis(mxn);
    deque<int> change;
    int64_t ans = 0;
    for(int i =0;i <n;i++) {
        int curr;
        cin >> curr;
        if(i < k) {
            if(vis[curr] == true) {
                change.push_back(i);
            }
            else {
                vis[curr] = true;
            }
        }
        else {
            if(vis[curr] == false) {
                int temp = change.front();
                ans += i - temp;
                change.pop_front();
                vis[curr] = true;
            }
        }
    }
    if((int)change.size()) {
        cout << -1;
    }
    else {
        cout << ans;
    }
}
 
int main()
{
	ios::sync_with_stdio(false); cin.tie(nullptr);
    int tt = 1;
    //cin >> tt;
    for(int case_num = 1; case_num <= tt; case_num++){
        //cout << "Case #" << case_num << ": ";
        solve();
        cout << "\n";
    }
 
    return 0;
}