题意
题解
OR , XOR , AND \text{OR},\text{XOR},\text{AND} OR,XOR,AND 位运算在二进制表示下不进位,各位之间的运算是独立的,那么可以按位进行处理。由于初始数字有上界限制,于是从高位向低位处理。
比较暴力的做法就是直接在每一位上分 0 , 1 0,1 0,1 两种情况进行计算。当初始数字为 1 1 1 时最终答案更优且初始数字不超出上界时,使这一位为 1 1 1,反之为 0 0 0。
#include <bits/stdc++.h>
using namespace std;
#define maxn 100005
int n, m, t[maxn];
char op[maxn][5];
int calc(int i, int x)
{
for (int j = 0; j < n; ++j)
{
int y = t[j] >> i & 1;
if (op[j][0] == 'A')
x &= y;
else if (op[j][0] == 'O')
x |= y;
else
x ^= y;
}
return x;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++i)
scanf(" %s%d", op + i, t + i);
int sum = 0, res = 0;
for (int i = 29; i >= 0; --i)
{
int x0 = calc(i, 0), x1 = calc(i, 1);
if (sum + (1 << i) <= m && x0 < x1)
res += 1 << i, sum += 1 << i;
else
res += x0 << i;
}
printf("%d\n", res);
return 0;
}
考虑位运算的特点,可以得到更高效的解法。当 OR \text{OR} OR 运算操作数为 1 1 1 或 AND \text{AND} AND 运算操作数为 0 0 0 时,最终这一位上的数字与初始状态无关;只用考虑其余情况,可以发现此时最终数字即初始数字异或 0 0 0 或 1 1 1,那么对于初始数字不超出上界且初始数字为 1 1 1 时答案更优的情况在这一位赋 1 1 1,反之为 0 0 0。
#include <bits/stdc++.h>
using namespace std;
#define maxn 100005
int n, m, t[maxn];
char op[maxn][5];
int main()
{
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++i)
scanf(" %s%d", op + i, t + i);
int sum = 0, res = 0;
for (int i = 29; i >= 0; --i)
{
int x = 0;
bool f = 0;
for (int j = 0; j < n; ++j)
{
int y = t[j] >> i & 1;
if (op[j][0] == 'A')
x &= y, f |= !y;
else if (op[j][0] == 'O')
x |= y, f |= y;
else
x ^= y;
}
if (f || x)
res += x << i;
else if (sum + (1 << i) <= m)
res += 1 << i, sum += 1 << i;
}
printf("%d\n", res);
return 0;
}