P2114 [NOI2014] 位运算

题意

传送门 P2114 [NOI2014] 起床困难综合症

题解

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值