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
#include <algorithm>
#include <cstdio>
#include <vector>

int n, k;

int count_different(const std::vector<int>& a) {
  std::vector<bool> present(n+1, false);
  for(int i = 0; i < n; ++i)
    present[a[i]] = true;
  return std::count(present.begin(), present.end(), true);
}

int main() {
  scanf("%d%d", &n, &k);

  std::vector<int> a(n);
  for(int i = 0; i < n; ++i)
    scanf("%d", &a[i]);

  const int diff_count = count_different(a);

  if(diff_count < k) {
    printf("-1\n");
    return 0;
  }

  int i = 0;
  int j = 0;
  long long result = 0LL;
  std::vector<bool> present(n+1, false);
  for(int i = 0; i < k; ++i) {
    if(present[a[i]]) {
      while(present[a[j]])
        ++j;

      std::swap(a[i], a[j]);
      result += j - i;
    }

    present[a[i]] = true;
  }

    printf("%lld\n", result);
}