uva 10718 Bit Mask (位运算)
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 |
Member of Elite Problemsetters' Panel
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std; long long n,l,r,a[100],b[100];
int cnta,cntb; void get(){
long long x=n;
cnta=0;cntb=0;
while(x>0){
a[cnta++]=x%2;
x/=2;
}
x=r;
while(x>0){
b[cntb++]=x%2;
x/=2;
}
} void computing(){
long long ans=0;
if(cntb>cnta){
for(int i=cntb-1;i>cnta-1;i--){
long long tmp=(long long)1<<(long long)i;//此处不强转,会超出int范围,wa了几次
if(b[i]==1){
l-=tmp;
r-=tmp;
ans+=tmp;
}
}
}
for(int i=cnta-1;i>=0;i--){
long long tmp=(long long)1<<(long long)i;
if(tmp<=l){
l-=tmp;
r-=tmp;
ans+=tmp;
}
else if(a[i]==0 && tmp<=r){
l-=tmp;
r-=tmp;
ans+=tmp;
}
}
printf("%lld\n",ans);
} int main(){
while(scanf("%lld%lld%lld",&n,&l,&r)!=EOF){
get();
computing();
}
return 0;
}
22 1 21
17 3 5
12 9 17
622 435 516
774 887 905
398 119 981
550 99 427
823 684 966
22398 14719 27341
29787 21141 30633
3113 24242 29497
5021 11052 19571
7359 6669 19790
993331 367623 921769
810986 227838 492138
987964 208251 1034287
1002648 217556 236589
680047 402532 767548
27719912 10747535 22001285
16862072 13339946 28844391
20421198 11724734 31928748
1541522 10226990 20764468
22651935 2478699 31095674
1995360670 908222743 1868651617
305542918 594331857 1426036714
1265639777 1580376576 1885248297
1442823820 658800174 1919310996
604563406 1050668699 2128532112
1 0 4294967295
9
4
17
435
905
625
409
712
14721
23460
29462
19554
17216
382924
237589
257219
234343
499600
14223127
16692359
13133233
19429997
10902496
957429345
1305069817
1880088222
704659827
1542920241
4294967294