题解:P17331 「TPOI-2A」Min Mex
分析
题意
给定一个长度为
思路
- 为了使 MEX 为
k ,则需构造出1 \sim k-1 且消除k 。将数组排序后,用最小的可用数去匹配目标t (从1 到k-1 )。 - 遍历数组,若
a_i \ge t ,将其减为t ,代价加a_i-t ,t 加1 。若遍历结束t < k ,则无解。 - 最后遍历剩余元素,若有等于
k 的数,需额外花费1 的代价将其减小。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
typedef long long ll;
ll a[N];
int main() {
int T;
cin >> T;
while (T--) {
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
if (k == 1) {
if (n > 0 && a[0] == 1) cout << -1 << endl;
else cout << 0 << endl;
continue;
}
ll ans = 0;
int t = 1, idx = 0;
while (idx < n && t < k) {
if (a[idx] >= t) {
ans += a[idx] - t;
t++;
}
idx++;
}
if (t != k) {
cout << -1 << endl;
continue;
}
while (idx < n) {
if (a[idx] == k) ans++;
idx++;
}
cout << ans << endl;
}
return 0;
}