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

int main()
{
    long long n,k;
    cin>>n>>k;
    vector<long long> v(n);
    for(long long i=0; i<n; ++i)
        cin>>v[i];
    vector<long long> count(n,0);
    long long types=0;
    for(long long i=0; i<k; ++i)
        ++count[v[i]-1];
    vector<long long> encountered(n,-1);
    long long changes=0;
    long long j=k;
    for(long long i=0; i<k; ++i)
        if(count[v[i]-1]>1)
            if(encountered[v[i]-1]==-1)
                encountered[v[i]-1]=1;
            else
            {
                while(j<n&&count[v[j]-1]>0)
                    ++j;
                if(j==n)
                {
                    changes=-1;
                    break;
                }
                changes+=(j-i);
                --count[v[i]-1];
                ++count[v[j]-1];
            }
    cout<<changes;
    return 0;
}