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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <deque>

int countBottlesTypes(std::vector<int> const &bottles)
{
    std::unordered_set<int> types(bottles.begin(), bottles.end());
    return types.size();
}

void swap(std::vector<int>& bottles, int left, int right)
{
    int tmp = bottles[left];
    bottles[left] = bottles[right];
    bottles[right] = tmp;
}

void solve(std::vector<int>& bottles, int left_bottles)
{
    int bottlesTypes = countBottlesTypes(bottles);
    if (bottlesTypes < left_bottles)
    {
        std::cout << -1 << std::endl;
        return;
    }
    std::unordered_map<int, int> indexes;
    indexes.reserve(bottlesTypes);
    std::unordered_map<int, bool> state;
    state.reserve(bottlesTypes);
    std::deque<int> order;
    for (int i = 0; i < bottles.size(); ++i)
    {
        int bottle = bottles.at(i);
        if (indexes.count(bottle) == 0)
        {
            state[bottle] = false;
            indexes[bottle] = i;
            order.push_back(bottle);
        }
    }
    unsigned long long count = 0;
    for (int i = 0;i<left_bottles; ++i)
    {
        if (order.empty())
            break;
        int bottle = bottles.at(i);
        if (state[bottle])
        {
            int changeBottle = order.front();
            int index = indexes[changeBottle];
            swap(bottles, i, index);
            count += index - i;
            state[changeBottle] = true;
            order.pop_front();
        }
        else 
        {
            state[bottle] = true;
            order.pop_front();
        }
    }

    std::cout << count << std::endl;

}

int main()
{
    int bottles, left_bottles;
    std::cin >> bottles >> left_bottles;

    std::vector<int> shelf;
    shelf.reserve(bottles);
    for (int i = 0; i < bottles; ++i)
    {
        int tmp;
        std::cin >> tmp;
        shelf.push_back(tmp);
    }

    solve(shelf, left_bottles);

    return 0;
}