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 |
题意:给定一个n, 和一个区间[l,r]。。在区间中找出一个最小数ni使得n | ni得到最大值。。
思路:这题用贪心来写。。我们知道或操作。只要有1进行或操作后会变成1。。
所以在进行贪心的时候。我们只要考虑n为1的位置。尽量用0去填,n为0的位置尽量用1去填。
不过在这之前要进行一个判断。就是如果当前一位如果填上1,会超过上界r,则只能填0.如果当前一位填上了0,会使得即使后面每位都填上1也到不了下界l,则只能填1.
然后由于n最大为2^32。。本来想用位运算的结果悲剧了。。最后自己写了个快速幂去把一个数拆解成01的二进制数。
代码:
#include <stdio.h>
#include <string.h>
long long n, l, r;
int vis[33];
long long num;
long long mi(long long d, int k) {//快速幂
if (k == 0)
return 1;
if (k == 1)
return d;
long long ans;
ans = mi(d * d, k / 2);
if (k % 2)
ans *= d;
return ans;
}
int main() {
while (~scanf("%lld%lld%lld", &n, &l, &r)) {
num = 0;
for (int i = 31; i >= 0; i --) {//转换为二进制
if (n >= mi(2, i)) {
n -= mi(2, i);
vis[i] = 1;
}
else
vis[i] = 0;
}
for (int i = 31; i >= 0; i --) {
if (mi(2, i) + num > r) continue;//如果填1超过上界
else if (mi(2, i) - 1 + num < l)//如果填0到不了下界
num += mi(2, i);
else {
if (!vis[i])//0的位置填1
num += mi(2, i);
}
}
printf("%lld\n", num);
}
return 0;
}