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

int main()
{
    ios_base::sync_with_stdio(false);
    int n, k;
    constexpr int MAXN = 5e5;
    cin >> n >> k;
    vector<bool> already_found(n+1, false);

    long long cost = 0;
    int counter = 0;

    for (int i=0; i < n && counter < k; ++i)
    {
        int a;
        cin >> a;
        if (!already_found[a]) {
            already_found[a] = true;
            cost += i - counter;
            counter++;
        }
    }

    if (counter == k) {
        cout << cost;
    }
    else {
        cout << -1;
    }
}