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
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back

using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
typedef pair <long long, long long> pll;

int n, k, unique_colors;
int a[500009], used[500009];
ll ans;

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);

    cin >> n >> k;
    for(int i = 1; i <= n; i++)
    {
        cin >> a[i];
    }

    int pt = 1;
    for(int i = 1; i <= k; i++)
    {
        pt = max(pt, i);
        if(unique_colors == k)
            break;

        if(used[a[i]] == 0)
        {
            unique_colors++;
            used[a[i]] = 1;
        }
        else
        {
            while(pt < n && used[a[pt + 1]] == 1)
            {
                pt++;
            }
            pt++;

            if(pt > n)
                break;

            ans += (ll)(pt - i);

            swap(a[i], a[pt]);

            if(used[a[i]] == 0)
            {
                used[a[i]] = 1;
                unique_colors++;
            }
        }
    }

    if(unique_colors == k)
        cout << ans << "\n";
    else
        cout << -1 << "\n";
}