Problem B: ChongBit
Time Limit: 1 Sec Memory Limit: 128 MB Submit: 42 Solved: 6 [ ][ ][ ]Description
Consider you are given a 32-bit unsigned integer N. You have to find a mask M such that L ≤ M ≤ R and N OR M is maximum. For example, if N is 100 and L = 50, R = 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, R where L ≤ R. Input is terminated by EOF.
Output
For each input, print in a line the minimum value of M, which makes N OR M maximum.
Sample Input
Sample Output
HINT
分析:
1.对于A|N,对于N取0的二进制位,A全都取1就可以使A|N最大化,可以直接令A为全1;但是,题中要求有多组解时输出最小值,故可令A=~N;
2.题目同时限制了输出结果的取值范围要在[L,R]之内,又要使A|N尽可能大,所以从~N的高位往地位处理,当L,R的二进制值相同时,将~N的该位值也改成这个值,如果L该位为0而R为1,~N的该位值为0时则说明已经满足<R,为1说明已经>L,当都满足过一次时则退出处理。
#includebool LB[32];bool RB[32];bool AB[32];int main(void){ unsigned N,L,R; while (~scanf("%u",&N)) { scanf("%u%u",&L,&R); unsigned A=~N; for (int i=0;i<32;i++) { AB[i]=A%2;LB[i]=L%2;RB[i]=R%2; A/=2;L/=2;R/=2; } bool s1=true,s2=true; for (int i=31;i>=0&&(s1||s2);i--) { if (AB[i]>RB[i]&&s2){AB[i]=RB[i];} else if (AB[i] LB[i]){s1=false;} } unsigned B=0; for (int i=31;i>=0;i--) { B=B<<1; B+=AB[i]; } printf("%u\n",B); } return 0;}