zoukankan      html  css  js  c++  java
  • Problem B: ChongBit

    Problem B: ChongBit

    Time Limit: 1 Sec  Memory Limit: 128 MB
    Submit: 42  Solved: 6
    [Submit][Status][Web Board]

    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

    100 50 60
    100 50 50
    100 0 100
    1 0 100
    15 1 15

    Sample Output

    59
    50
    27
    100
    1

    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,当都满足过一次时则退出处理。

    #include <cstdio>
    
    
    bool 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){AB[i]=LB[i];}
                if (AB[i]<RB[i]){s2=false;}
                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
    ",B);
        }
    
    
        return 0;
    }
    View Code
  • 相关阅读:
    C语言——总结回顾
    C语言——第十四、十五周作业
    题目思路——统计素数并求和
    题目思路——单词长度
    C语言——第七周作业
    C语言——第六周作业
    C语言——第四次作业
    C语言——第三次作业
    C语言——第二次作业
    C语言——第一次作业
  • 原文地址:https://www.cnblogs.com/weilongping/p/3505884.html
Copyright © 2011-2022 走看看