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
#include <cstdio>
#include <array>
#include <cstdint>
#include <exception>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <numeric>

int main(int argc, char** argv) {
    int32_t n, k;
    std::unordered_set<int32_t> set;
    std::scanf("%d %d", &n, &k);

    std::vector<int32_t> a(n);

    for(int32_t i = 0; i < n; ++i) {
        std::scanf("%d", &a[i]);
    }

    set.insert(*a.begin());

    uint64_t count = 0;

    for(auto iter1 = ++a.begin(); iter1 != (a.begin() + k); ++iter1) {
        if(set.find(*iter1) != set.end()) {
            auto const iter2 = std::find_if(iter1, a.end(), [&set](auto x) {
                return set.find(x) == set.end();
            });

            if(iter2 == a.end()) {
                std::puts("-1");
                std::exit(0);
            }

            count += iter2 - iter1;
            set.insert(*iter2);
            std::swap(*iter1, *iter2);
        }
    }

    std::printf("%llu\n", count);

    return 0;
}