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
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const ll MAXN = 5e5 + 7;
vector<bool> seen(MAXN);

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    ll n, k;
    cin >> n >> k;
    vector<ll> bottles(n);
    for (auto& bottle : bottles)
        cin >> bottle;
    
    queue<pair<ll, ll>> que;
    for (ll i = 0; i < n; i++)
        if (seen[bottles[i]] == false){
            que.push({bottles[i], i});
            seen[bottles[i]] = true;
        }
    
    //resetujemy seen
    for (auto& bottle : bottles)
        seen[bottle] = false;

    if ((ll)que.size() < k){
        cout << -1 << "\n";
        return 0;
    }

    ll moves = 0;
    for (ll i = 0; i < k; i++){
        if (bottles[i] == -1)
            continue;
        if (seen[bottles[i]] == false)
            seen[bottles[i]] = true;
        else{
            while (seen[que.front().first])
                que.pop();
            moves += que.front().second - i;
            seen[que.front().first] = true;
        }
    }

    cout << moves << "\n";

    return 0;
}