AcWing - 998 - 起床困难症(暴力/位运算性质)

题目点我OvO

题目大意

  让你从[0, m]里面选一个数,问他经过n次位运算之后的数最大是多少。

思路

  这里我们要清楚位运算的一个性质,与、或、异或这些位运算都是没有进位的,也就是说对于一个二进制数,它经过若干次位运算之后第k位是0还是1只和这个二进制数的第k位有关。知道这条性质之后我们只要枚举每位的情况就行了因为t<=1e9,所以我们只要枚举31个二进制位是0还是1(注意先从高位开始,因为高位上的一个1比高位0低位全是1还要大)就行了。另外还有一个小技巧,1<<k&num可以判断num二进制位第k位是0还是1(k从0开始)。

代码

//https://www.cnblogs.com/shuitiangong/
#include<set>
#include<map>
#include<list>
#include<stack>
#include<queue>
#include<cmath>
#include<cstdio>
#include<cctype>
#include<string>
#include<vector>
#include<climits>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define endl '\n'
#define rtl rt<<1
#define rtr rt<<1|1
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
#define maxx(a, b) (a > b ? a : b)
#define minn(a, b) (a < b ? a : b)
#define zero(a) memset(a, 0, sizeof(a))
#define INF(a) memset(a, 0x3f, sizeof(a))
#define IOS ios::sync_with_stdio(false)
#define _test printf("==================================================\n")
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> P2;
const double pi = acos(-1.0);
const double eps = 1e-7;
const ll MOD =  1000000007LL;
const int INF = 0x3f3f3f3f;
const int _NAN = -0x3f3f3f3f;
const double EULC = 0.5772156649015328;
const int NIL = -1;
template<typename T> void read(T &x){
    x = 0;char ch = getchar();ll f = 1;
    while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
    while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
const int maxn = 1e5+10;
ll info[maxn][2], n, m;
void solve(ll &num) {
    for (int j = 0; j<n; ++j) {
        if (info[j][0]==1) num &= info[j][1];
        else if (info[j][0]==2) num |= info[j][1];
        else num ^= info[j][1];
    }
}
int main(void) {
    while(~scanf("%lld%lld", &n, &m)) {
        for (int i = 0; i<n; ++i) {
            char str[5];
            scanf("%s%lld", str, &info[i][1]);
            if (str[0]=='A') info[i][0] = 1;
            else if (str[0]=='O') info[i][0] = 2;
            else info[i][0] = 3;
        }
        ll sum = 0, ans = 0, t0 = 0;
        solve(t0);
        for (int i = 30; i>=0; --i) { //枚举每一个二进制位
            if (1<<i&t0) { ////如果是0就能白嫖一位
                ans += 1<<i;
                continue;
            }
            ll t1 = 1<<i;
            if (sum + t1 > m) continue; //如果当前的数加起来比m大就跳过
            solve(t1);
            if (1<<i&t1) {
                sum += 1<<i;
                ans += 1<<i;
            }
        }
        printf("%lld\n", ans);
    }
    return 0;
}
posted @ 2020-03-16 20:36  shuitiangong  阅读(153)  评论(0编辑  收藏  举报