[UVA][Greedy] 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 |
如果原本那個 bit 為 1, 選擇與否取決於有沒有大於低限
原本那個 bit 為 0, 選擇與否取決於有沒有小於上限
#include <stdio.h>
int main() {
long long N, L, R, ans, l, r;
while(scanf("%lld %lld %lld", &N, &L, &R) == 3) {
ans = 0;
long long i;
for(i = 31; i >= 0; i--) {
if(N&(1LL<<i)) {
r = ans + (1LL<<i);
if(r <= L)
ans += 1LL<<i;
} else {
l = ans + (1LL<<i);
if(l <= R)
ans += 1LL<<i;
}
}
printf("%lld\n", ans);
}
return 0;
}
神人寫出的神解法<(_ _)>
先看看學習學習~
1LL 是何物?
為什麼大大這麼厲害呀
我常常望著程式碼發楞...
(看了很多大大的程式碼(感謝PO碼)
其實很多仍看不太懂
幸好仍有些微的進步)
想必你也能夠理解當初我也是打得很差勁的,
現在只是比較好一點而已 2012-06-05 20:08:17