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
//
//  main.cpp
//  ora
//
//  Created by Wojciech Siwko on 07/12/2021.
//

#include <iostream>
#include <vector>
#include <unordered_set>
#include <queue>
#include <utility>

using namespace std;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int n, k; cin >> n >> k;
    vector<int> t(n);
    unordered_set<int> s;
    unordered_set<int> inq;
    queue<pair<int, int>> q;
    queue<int> inc_pos;
    long long res = 0;
    int correct = 0;
    for (int i = 0; i < t.size(); i++) {
        cin >> t[i];
        if (i < k) {
            if (s.find(t[i]) == s.end()) {
                s.insert(t[i]);
                correct++;
            }
            else {
                inc_pos.push(i);
            }
        }
        else {
            if (inq.find(t[i]) == inq.end() && s.find(t[i]) == s.end()) {
                inq.insert(t[i]);
                q.push({ i, t[i] });
            }
        }
    }
    while (correct != k && !q.empty()) {
        pair<int, int> p = q.front();
        int a = p.first; int b = p.second;
        int c = inc_pos.front();
        res += a - c;
        correct++;
        inc_pos.pop();
        q.pop();
    }
    if (correct != k) cout << -1 << endl;
    else cout << res << endl;
    return 0;
}