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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <iostream>
#include <cstdio>
#include <string>
#include <sstream> 
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <ctime>
#include <cassert>
using namespace std;

#define assert_range(x,a,b) assert((a) <= (x) and (x) <= (b))
using ll = long long;
const int INF = 1e9;

ll solve(const vector<int>& a, int k) {
    int n = a.size();
    vector<bool> seen(n);
    vector<int> ls;
    for (int i = 0; i < k; ++i) {
        if (seen[a[i]]) {
            ls.push_back(i);
        } 
        seen[a[i]] = true;
    }
    vector<int> rs;
    for (int i = k; i < n; ++i) {
        if (!seen[a[i]] && rs.size() < ls.size()) {
            rs.push_back(i);
        }
        seen[a[i]] = true;
    }
    if (rs.size() < ls.size()) {
        return -1;
    }
    ll res = 0;
    int m = ls.size();
    for (int i = 0; i < m; ++i) {
        int x = ls[m-1-i];
        int y = rs[i];
        res += (k-1-x) + (y-k) + 1;
    }
    return res;
}

ll solve_fast(const vector<int>& a, int k) {
    int n = a.size();
    vector<bool> seen(n);
    ll res = 0;

    int cnt_left = 0;
    for (int i = 0; i < k; ++i) {
        if (seen[a[i]]) {
            res += k-1-i;
            cnt_left += 1;
        } 
        seen[a[i]] = true;
    }
    int cnt_right = 0;
    for (int i = k; i < n; ++i) {
        if (!seen[a[i]] && cnt_left > cnt_right) {
            res += i-k;
            cnt_right += 1;
        }
        seen[a[i]] = true;
    }
    if (cnt_right < cnt_left) {
        return -1;
    }
    res += cnt_left;
    return res;
}

int main() {
    // ios_base::sync_with_stdio(0);
    int n, k;
    scanf("%d %d", &n, &k);
    // cin >> n >> k;
    vector<int> a(n);
    for (int i = 0; i < n; ++i) {
        // cin >> a[i];
        scanf("%d", &a[i]);
        a[i] -= 1;
    }
    auto res = solve_fast(a, k);
    // cout << res << endl;
    printf("%lld\n", res);
    return 0;
}