Problem A | Bit Mask |
Time Limit | 1 Second |
In bit-wise expression, mask is a common term. You can get a certain bit-pattern using mask. For example, if you want to make first 4 bits of a 32-bit number zero, you can use 0xFFFFFFF0 as mask and perform a bit-wise AND operation. Here you have to find such a bit-mask.
Consider you are given a 32-bit unsigned integer N. You have to find a mask M such that L ≤ M ≤ U and N OR M is maximum. For example, if N is 100 and L = 50, U = 60 then M will be 59 and N OR M will be 127 which is maximum. If several value of M satisfies the same criteria then you have to print the minimum value of M.
Input
Each input starts with 3 unsigned integers N, L, U where L ≤ U. Input is terminated by EOF.
Output
For each input, print in a line the minimum value of M, which makes N OR M maximum.
Look, a brute force solution may not end within the time limit.
Sample Input | Output for Sample Input |
100 50 60 | 59 |
分析:
题目说明暴力法会超时。
采用位比较法。
代码:
#include
#include
using namespace std;
int main()
{
unsigned n, l, u;
while(cin >> n >> l >> u){
bitset<32> bitn(n);
bitset<32> bitl(l);
bitset<32> bitu(u);
bitset<32> bitm;
int gtl = 0;
int ltu = 0;
for(int i = 31; i >= 0; i--){
if(bitu[i] == 1 && bitl[i] == 1){
if(gtl == 0 || bitn[i] == 0)
bitm[i] = 1;
else{
bitm[i] = 0;
ltu = 1;
}
}else if(bitu[i] == 1 && bitl[i] == 0){
if(bitn[i] == 0){
bitm[i] = 1;
if(gtl == 0)
gtl = 1;
}else{
bitm[i] = 0;
ltu = 1;
}
}else if(bitu[i] == 0 && bitl[i] == 1){
if(bitn[i] == 0){
if(ltu == 1)
bitm[i] = 1;
}else if(gtl == 0){
bitm[i] = 1;
}
}else if(bitu[i] == 0 && bitl[i] == 0){
if(bitn[i] == 0){
if(ltu == 1){
bitm[i] = 1;
if(gtl == 0)
gtl = 1;
}
}
}
}
cout << bitm.to_ulong() << endl;
}
return 0;
}
别人的简洁代码:
- #include <cstdio>
- #include <cmath>
- #define repd(i, a, b) for (int i = (a); i >= (b); i--)
- const int MAXN = 100;
- int main() {
- long long n, l, u, m, t;
- while (scanf("%lld%lld%lld", &n, &l, &u) != EOF) {
- int len = ceil(log(u) / log(2));
- m = 0;
- repd(i, len, 1) {
- t = m | (1LL << (i - 1)); //1
- if (n >> (i - 1) & 1) {
- if (t <= l) m = t;
- }
- else {
- if (t <= u) m = t;
- }
- }
- printf("%lld\n", m);
- }
- return 0;
- }