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

typedef long long int lli;

const int MAX = 500500;
int bottles[MAX];
bool used[MAX];

int main() {
  int N, K;
  lli sum = 0;

  scanf("%d%d", &N, &K);
  for (int i = 0; i < N; ++i) {
    scanf("%d", bottles + i);
  }

  int i = 0, place, j;
  for (; i < K && !used[bottles[i]]; ++i) {
    used[bottles[i]] = true;
  }

  for (place = i, j = i + 1; place < K; ++place) {
    while (j < N && used[bottles[j]]) {
      ++j;
    }
    if (j == N) {
      break;
    }
    used[bottles[j]] = true;
    sum += j - place;
  }

  printf("%lld", (place == K) ? sum : -1);

  return 0;
}