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

using namespace std;
typedef long long ll;
const int N = 5 * 100 * 1000 + 7;
int tab[N], czy[N];
vector<int> l, p;

void Solve()
{
    int n, k;
    ll w;
    w = 0LL;
    cin >> n >> k;
    for(int i = 1; i <= k; ++i)
    {
        cin >> tab[i];
        if(czy[tab[i]] == 1)
            l.push_back(i);
        czy[tab[i]] = 1;
    }
    for(int i = k + 1; i <= n; ++i)
    {
        cin >> tab[i];
        if(czy[tab[i]] == 0)
            p.push_back(i);
        czy[tab[i]] = 1;
    }
    if(p.size() < l.size())
    {
        cout << -1 << "\n";
        return;
    }
    for(int i = 0; i < (int)l.size(); ++i)
    {
        w += (ll)(k - l[i] - (l.size() - i - 1));
        w += (ll)(p[i] - (k - l.size() + i + 1));
    }
    cout << w << "\n";
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    Solve();

    return 0;
}