由于有式子 ,所以考虑按位贪心。
假设当前正在考虑第 位,那么把第 个数的第 位变成 的代价为 。把所有数的代价算出来,取前 小的代价,如果加起来不大于 ,那么把答案的第 位设为 肯定最优。把前 小的数的贡献加到对应的数上,然后删掉所有第 位为 的数(因为这些数是不能被选择的),继续判断下一位即可。
#include <algorithm>
#include <iostream>
using namespace std;
using LL = long long;
const int kN = 2e5 + 1;
int k, n, m, a[kN], b[kN], d[kN], ans, _a[kN];
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m >> k;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
for (int i = 31; i >= 0 && n >= k; --i) {
for (int j = 1; j <= n; ++j) {
d[j] = j;
b[j] = max(0LL, (1LL << i) - (a[j] & ((1LL << i + 1) - 1))); // 计算代价
}
sort(d + 1, d + n + 1, [](int i, int j) { return b[i] < b[j]; });
LL s = 0;
for (int j = 1; j <= k; ++j) { // 选代价前 k 小的数
s += b[d[j]];
}
if (s <= m) { // 如果可行
m -= s, ans |= 1 << i; // 将答案的这一位设为 1
for (int j = 1; j <= k; ++j) { // 修改对应的数
a[d[j]] += b[d[j]];
}
int _n = 0;
for (int j = 1; j <= n; ++j) { // 删掉不能选的数
if (a[j] >> i & 1) {
_a[++_n] = a[j];
}
}
copy_n(_a + 1, n = _n, a + 1);
}
}
cout << ans;
return 0;
}