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
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;


int main() {
    std::ios::sync_with_stdio(false);
    int n, k;
    cin >> n >> k;
    vector<int> bottles;
    int x;
    unordered_map<int, int> count;
    for(int i = 0; i < n; ++i) {
        cin >> x;
        bottles.push_back(x);
        if (i < k) {
            count[x] += 1;
        }
    }

    int left = k - 1, right = k;
    long long results = 0;
    while (left >= 0) {
        int cur = bottles[left];
        if (count[cur] == 1) { // already unique bottle
            --left;
            continue;
        }
        // cout << "left=" << left << " right=" << right << endl;

        int cand = bottles[right];
        while(right < n && count[cand] > 0) {
            cand = bottles[++right];
        }
        if(right == n) { // no candidate for swap
            results = -1;
            break;
        }
        
        results += right - left;
        ++count[cand];
        --count[cur];
        ++right;
        --left;
    }
    cout << results << endl;
}