UVA 10718 Bit Mask
In bit-wise expression, mask was a common term. You can get a certain bit-pattern using mask. For example, if your want to make first 4 bits of a 32-bit number zero, you can use 0XFFFFFFF0 as mask and perform a bit-wi SE and operation. Here are the such a bit-mask to find.
Consider you given a 32-bit unsigned integerN. You had to find a mask M such that l≤m≤u and N OR m is maximum. For example, ifn is and L = A, U = $ thenM would be, and N OR M would b E 127 which is maximum. If several value of m satisfies the same criteria then you had to print the minimum value ofm.
Input
Each of the 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 makesN OR m maximum.
Look, a brute-solution may not end within the time limit.
Sample Input |
Output for Sample Input |
100 50 60 100 50 50 100 0 100 1 0 100 15 1 15 |
59 50 27 100 1 |
The main topic: Each group of data contains three valid data: 1) N; 2) L; 3) U to find the maximum number of values of M and n done or calculated between l~u and the minimum value of itself.
Problem-solving ideas: At the outset, direct use or operation + violence, not hesitate to time out. Then use another method, first to convert n into binary existence an array, and then from the high start to traverse, construct m, if the current bit is 0, if not exceed the upper limit of the case, m of the bit is 1, if the current bit is 1, the position of M is assigned to 1 when the lower limit is reached.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm> #define M 32typedef Long ll;using namespace Std;ll N, L, U, b[m + 1];int a[m + 1];int Change (int. *t, LL A) {for (int i = 0; I & Lt M i++) {t[i] = a% 2;a/= 2;}} int main () {b[0] = 1;for (int i = 1; i < M; i++) {b[i] = b[i-1] * 2;} while (scanf ("%lld%lld%lld", &n, &l, &u) = = 3) {ll-ans = 0, Temp;change (A, N); for (int i = M-1; I >= 0; i--) {if (! A[i] {temp = ans + b[i];if (temp <= U) {//when the bit of n is 0, then 1ans + = B[i] is selected without exceeding the upper limit;}} else {temp = ans + b[i]-1;if (Temp < L) {//If the bit is selected 1, up to the lower limit, then 1, if the lower limit can be reached, in order to maintain the minimum ans, select 0ans + = B[i];}} printf ("%lld\n", ans);} return 0;}
UVA 10718 bit Mask (bitwise operation)