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
#include <iostream>
#include <set>

using namespace std;

int main() {
    int n, k;
    cin >> n >> k;
    set<int> unique_bottles;

    int m;
    cin >> m;
    unique_bottles.insert(m);
    int next_good_pos = 1;
    int totalcost = 0;

    if (k == 1) {
        cout << 0 << endl;
        return 0;
    }

    for (int i = 1; i < n; ++i) {
        cin >> m;
        bool fresh_bottle = (unique_bottles.find(m) == unique_bottles.end());
//        cerr << "-------------------------------------" << endl;
//        cerr << "BOTTLE: " << m << endl;
        if (fresh_bottle) {
//            cerr << "FRESH! ! ! ! ! ! ! !" << endl;
            int movecost = i - next_good_pos;
            totalcost += movecost;
            next_good_pos++;
            unique_bottles.insert(m);
//            cerr << "MOVECOST:  " << movecost << endl;
//            cerr << "TOTALCOST: " << totalcost << endl;
//            cerr << "NEXT BOTTLE WILL BE MOVED TO " << next_good_pos << endl;
            if (next_good_pos == k) {
                cout << totalcost << endl;
                return 0;
            }
        }
    }
    cout << -1 << endl;
    return 0;
}