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

#define MAXN 1000000
int N, K;
bool seen[MAXN];

int main() {
  int seen_cnt = 0;
  int res = 0;
  scanf("%d %d", &N, &K);
  for (int i = 0; i < N; ++i) seen[i] = false; 
  int cmark; 
  for (int i = 0; i < N; ++i) {
    scanf("%d", &cmark); 
    if (i < K) {
      if (seen[cmark]) {
        res += (K - i);
      } else {
        seen[cmark] = true;
        seen_cnt += 1;
      }  
    } else { // i >= K 
      if (seen_cnt == K) {
        printf("%d\n", res);
        return 0;
      }
      if (!seen[cmark]) {
        seen[cmark] = true;
        seen_cnt += 1;
        res += (i - K);
      } 
    }
  }
  if (seen_cnt == K) {
    printf("%d\n", res);
  } else {
    printf("-1\n");
  }
  return 0;
}