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

#define FOR(name, p, upper) for(int name = p; name < upper; ++name)

vector<int> shelf;
queue <int> position;
vector<bool> dif, change;

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    
    int n, k;
    bool w = false;
    long long time = 0;
    cin >> n >> k;
    shelf.resize(n);
    dif.resize(n+1);
    change.resize(n);
    FOR(i, 0, n)
    {
        cin >> shelf[i];     
        if(dif[shelf[i]])
        {
            change[i] = true;
        }  
        else
        {
            dif[shelf[i]] = true;
            position.push(i);
        }
    }
    FOR(i, 0, k)
    {
        if(change[i])
        {
            w = true; 
            break;
        }
    }
    if(w)
    {
        int i = 0;
        while(position.size() > 0)
        {
            if(position.front() == i)
                position.pop();
            if(change[i] == true)
            {
                time += (position.front()-i);;
                change[i] = 0;
                change[position.front()] = 1;
                position.pop();
            }
            i++;
        } 
        if(time == 0)  
            cout << -1;
        else
            cout << time;
    }
    else
    {
        cout << 0;
    }
    
}