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

int main() {
    int MAX = 500001;
    int n, k, a[MAX], m[MAX] = {0,}, uniq = 0, good[MAX] = {0,};
    long long swaps = 0;
    cin >> n >> k;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    for (int i = 0; i < n && uniq < k; i++) {
        if (m[a[i]] == 0) {
            uniq++;
            good[i] = 1;
            m[a[i]] = 1;
        }
    }
    if (uniq < k) {
        cout << -1 << endl;
        return 0;
    }
    int bad = 0;
    for (int i = 0; i < n; i++) {
        if (good[i] == 0) {
            bad = i;
            break;
        }
    }
    for (int i = bad + 1; i < n; i++) {
        if (good[i]) {
            swaps += i - bad;
            bad++;
        }
    }
    cout << swaps << endl;     
    return 0;
}