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
#include <bits/stdc++.h>
using namespace std;

typedef long long int LL;

int n, k, a;
int iLeft, iRight;
LL res;
unordered_set<int> notUsableNumbers;
vector<int> leftIndexesToSwap, availableRightIndexes;
unordered_set<int> numbersPresentOnRight;


int main()
{
    ios_base::sync_with_stdio(0);

    cin >> n >> k;
    for(int i = 0; i < k; ++i)
    {
        cin >> a;

        if(notUsableNumbers.find(a) == notUsableNumbers.cend())
        {
            notUsableNumbers.insert(a);
        }
        else
        {
            leftIndexesToSwap.push_back(i);
        }
    }

    for(int i = k; i < n; ++i)
    {
        cin >> a;

        if(notUsableNumbers.find(a) == notUsableNumbers.cend())
        {
            availableRightIndexes.push_back(i);
            notUsableNumbers.insert(a);
        }
    }

    if(availableRightIndexes.size() < leftIndexesToSwap.size())
    {
        cout << -1 << endl;
        return 0;
    }

    while(iLeft < leftIndexesToSwap.size() && iRight < availableRightIndexes.size())
    {
        res += availableRightIndexes[iRight] - leftIndexesToSwap[iLeft];
        ++iLeft; ++iRight;
    }

    cout << res << endl;

    return 0;
}