[题目链接]
https://www.lydsy.com/JudgeOnline/problem.php?id=3668
[算法]
从高位向低位贪心即可
时间复杂度 : O(30N)
[代码]
#include<bits/stdc++.h> using namespace std; #define MAXLOG 30 const int MAXN = 1e5 + 10; int n,m,ans; int value[MAXN],t[MAXN]; char op[5]; template <typename T> inline void read(T &x) { int f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } inline bool ok(int x,int val) { int num; num = (val == 0) ? 0 : 1 << x; for (int i = 1; i <= n; i++) { if (value[i] == 1) num &= t[i]; if (value[i] == 2) num |= t[i]; if (value[i] == 3) num ^= t[i]; } if (num & (1 << x)) return true; else return false; } int main() { scanf("%d%d",&n,&m); for (int i = 1; i <= n; i++) { scanf("%s%d",op,&t[i]); if (strcmp(op,"AND") == 0) value[i] = 1; if (strcmp(op,"OR") == 0) value[i] = 2; if (strcmp(op,"XOR") == 0) value[i] = 3; } for (int i = MAXLOG; i >= 0; i--) { if (ok(i,0)) { ans += 1 << i; continue; } if (ok(i,1) && m >= 1 << i) { m -= 1 << i; ans += 1 << i; } } printf("%d ",ans); return 0; }