AtCoder Regular Contest 146 B Plus and AND
Plus and AND
贪心
从高位开始逐位枚举,如果当前位能够在 \(k\) 的代价内将所有数字都变成 \(1\),则认为结果的当前位是 \(1\),如果凑这一位利用了低位的 \(1\),则要将其全部置为 \(0\)
重复这个过程
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 10;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll n, m, k;
cin >> n >> m >> k;
vector<ll>a(n);
for(int i=0; i<n; i++) cin >> a[i];
vector<ll>num(n, 0), temp(n);
ll ans = 0;
for(int i=31; i>=0; i--)
{
for(int j=0; j<n; j++)
{
temp[j] = num[j];
if(a[j] >> i & 1) temp[j] += 0;
else temp[j] += (1ll << i) - (a[j] % (1ll << i));
}
sort(temp.begin(), temp.end());
ll sum = 0;
int f = 0;
for(int j=0; j<k; j++) sum += temp[j];
if(sum <= m) f = 1;
if(f)
{
ans |= 1ll << i;
for(int j=0; j<n; j++)
{
if(a[j] >> i & 1) num[j] = num[j];
else
{
num[j] += (1ll << i) - (a[j] % (1ll << i));
a[j] = 0;
}
}
}
}
cout << ans << endl;
return 0;
}