分析
题意
给定一个长度为 n 的数组,每次操作可以选择一个数 ai 和一个整数 x(0≤x<ai),花费 x 的代价将 ai 变成 ai−x。求使数组 mex 为 k 的最小总代价,无法实现则输出 −1。
思路
- 为了使 MEX 为 k,则需构造出 1∼k−1 且消除 k。将数组排序后,用最小的可用数去匹配目标 t(从 1 到 k−1)。
- 遍历数组,若 ai≥t,将其减为 t,代价加 ai−t,t 加 1。若遍历结束 t<k,则无解。
- 最后遍历剩余元素,若有等于 k 的数,需额外花费 1 的代价将其减小。
代码
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
| #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; }
|