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

int tab[500005];
bool wasthere[500005];
long long dist;
queue<int>positions_with_repeated;

int main(){
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int n, k;
  cin >> n >> k;
  for(int i = 0; i < n; i++){
    cin >> tab[i];
    if(!wasthere[tab[i]] && k > 0){
      wasthere[tab[i]] = true;
      k--;
      if(!positions_with_repeated.empty()){
        dist += i - positions_with_repeated.front();
        positions_with_repeated.pop();
      }
      continue;
    }
    positions_with_repeated.push(i);
  }
  if(k > 0)
    cout << -1 << '\n';
  else
    cout << dist << '\n';
  return 0;
}