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 rst 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 nd such a bit-mask.
Consider you are given a 32-bit unsigned integer N. You have to nd 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 satis es 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
100 50 60
100 50 50
100 0 100
1 0 100
15 1 15
Sample Output
59
50
27
100
1
题意:就是让你求在给定的区间内【L,U】,让你求一个数N与区间内的数求或的最大值最后输出区间内的这个数。
思路:刚开始就简单的枚举一遍,TLE了,很无语,不知道如何下手,看来别人的博客,用位操作,首先4个字节32 位,就从31 位开始计算
AC 代码:
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
int n,l,u;
unsigned int m;
while(~scanf("%d%d%d",&n,&l,&u)){
m = 0;
for(int i = 31;i >= 0;i--){
if(m + (1 << i) <=u &&( (n & (1 << i) ) == 0||( m < l&& (l& (1<<i) ) ) ) ) {//这步不好理解首先要满足m不能比u大并且(满足n的二进制位和1 << i的各个位置上都有1或者当前数<l并且n的二进制位与1 << I 的二进制位上有相同的1)
m+=(1<<i);
}
}
printf("%u\n",m);
}
return 0;
}
位操作就是坑,每次都会想不通,每日次都不长记性,要好好想想了