#include <bits/stdc++.h>
#include<algorithm>
#include <math.h>
using namespace std;
#define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define pb push_back
#define pii pair<int, pair<int, int>>
#define mp make_pair
#define f first
#define s second
#define all(x) (x).begin(), (x).end()
int main() {
fast_io;
int n, k;
vector<int> l;
cin >> n >> k;
int last;
int cnt = 0;
vector<bool> include(n, false);
for (int i = 0; i < n; i++){
int x;
cin >> x;
l.pb(x);
}
vector<bool> seen(n, false);
for (int i = 0; i < n; i++){
if (seen[l[i]] == false) {
include[i] = true;
if (cnt == k - 1) {
last = i;
cnt += 1;
break;
}
else {
cnt += 1;
}
seen[l[i]] = true;
}
}
if (cnt < k) {
cout << -1;
}
else {
long long ans = 0;
int sub = 0;
for (int i = last - 1; i > 0; i--) {
if (!include[i]) {
ans += (last - i - sub);
sub += 1;
}
}
cout << ans;
}
}
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 | #include <bits/stdc++.h> #include<algorithm> #include <math.h> using namespace std; #define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define pb push_back #define pii pair<int, pair<int, int>> #define mp make_pair #define f first #define s second #define all(x) (x).begin(), (x).end() int main() { fast_io; int n, k; vector<int> l; cin >> n >> k; int last; int cnt = 0; vector<bool> include(n, false); for (int i = 0; i < n; i++){ int x; cin >> x; l.pb(x); } vector<bool> seen(n, false); for (int i = 0; i < n; i++){ if (seen[l[i]] == false) { include[i] = true; if (cnt == k - 1) { last = i; cnt += 1; break; } else { cnt += 1; } seen[l[i]] = true; } } if (cnt < k) { cout << -1; } else { long long ans = 0; int sub = 0; for (int i = last - 1; i > 0; i--) { if (!include[i]) { ans += (last - i - sub); sub += 1; } } cout << ans; } } |
English