#define make_pair mp #define emplace_back pb #include <bits/stdc++.h> using namespace std; mt19937 mt_rand(time(0)); const int N = 5e5 + 5; int n, k, tab[N]; bool is[N]; int main() { scanf("%d%d", &n, &k); for(int i=1;i<=n;i++) { scanf("%d", &tab[i]); is[tab[i]] = true; } int cnt = 0; for(int i=1;i<=n;i++) cnt += is[i]; if(cnt < k) { printf("-1\n"); return 0; } for(int i=1;i<=n;i++) is[i] = 0; cnt = 0; long long res = 0; for(int i=1;i<=k;i++) { if(is[tab[i]]) { cnt++; res += k - i; } is[tab[i]] = 1; } long long cnt2 = cnt; long long cc = (cnt2 - 1) * cnt2 / 2; res -= cc; cnt = k - cnt + 1; if(cnt <= k) for(int i=k+1;i<=n;i++) { if(!is[tab[i]]) { is[tab[i]] = 1; res += i - cnt; cnt++; if(cnt == k + 1) break; } } printf("%lld\n", res); return 0; }
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 | #define make_pair mp #define emplace_back pb #include <bits/stdc++.h> using namespace std; mt19937 mt_rand(time(0)); const int N = 5e5 + 5; int n, k, tab[N]; bool is[N]; int main() { scanf("%d%d", &n, &k); for(int i=1;i<=n;i++) { scanf("%d", &tab[i]); is[tab[i]] = true; } int cnt = 0; for(int i=1;i<=n;i++) cnt += is[i]; if(cnt < k) { printf("-1\n"); return 0; } for(int i=1;i<=n;i++) is[i] = 0; cnt = 0; long long res = 0; for(int i=1;i<=k;i++) { if(is[tab[i]]) { cnt++; res += k - i; } is[tab[i]] = 1; } long long cnt2 = cnt; long long cc = (cnt2 - 1) * cnt2 / 2; res -= cc; cnt = k - cnt + 1; if(cnt <= k) for(int i=k+1;i<=n;i++) { if(!is[tab[i]]) { is[tab[i]] = 1; res += i - cnt; cnt++; if(cnt == k + 1) break; } } printf("%lld\n", res); return 0; } |