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
#include <bitset>
#include <iostream>
#include <vector>

std::bitset<500000> seen;

int main(void) {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(nullptr);
  int n, k;
  std::cin >> n >> k;
  int a[n];
  for (int i = 0; i < n; i++) {
    std::cin >> a[i];
  }
  std::vector<int> bads, goods;
  for (int i = 0; i < k; i++) {
    if (seen[a[i]]) {
      bads.push_back(i);
    }
    seen.set(a[i]);
  }
  int needed = bads.size();
  for (int i = k; i < n && needed; i++) {
    if (!seen[a[i]]) {
      goods.push_back(i);
      seen.set(a[i]);
      needed--;
    }
  }
  if (needed) {
    std::cout << -1 << std::endl;
  } else {
    long long result = 0;
    for (int i = 0; i < bads.size(); i++) {
      result += goods[i] - bads[i];
    }
    std::cout << result << std::endl;
  }
  return 0;
}