uva-10718-贪心

题意:输入unsigned int N,L,U,找出一个M(L<=M<=U)使得N | M最大,如果有多个M使得N | M最大,取最小的M,

解题思路:贪心,从最高位开始,判断是否应该置为0还是置为1,如果置0,那么一定要判断当前的ans加上剩下的数是否还在[L,U]之间.

如果不在,一定要置1.

#include "pch.h"
#include <string>
#include<iostream>
#include<map>
#include<memory.h>
#include<vector>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<math.h>
#include<iomanip>
#include<bitset>

namespace cc
{
    using std::cout;
    using std::endl;
    using std::cin;
    using std::map;
    using std::vector;
    using std::string;
    using std::sort;
    using std::priority_queue;
    using std::greater;
    using std::vector;
    using std::swap;
    using std::stack;
    using std::bitset;


    unsigned int N, L, U;
    unsigned int a[32];
    
    void init() 
    {
        for (int i=0;i<32;i++) 
        {
            a[i] = (1 << i) - 1;
        }
    
    }
    int findMaxBit(unsigned U) 
    {
        int max = 0;
        int i = 0;
        while (i < 32)
        {
            if ((U >> i) & 1)
                max = i;
            ++i;
        }
        return max;
    }
    void solve()
    {
        init();
        while (cin>>N>>L>>U) 
        {
            unsigned int ans = 0;
            unsigned int curMax = N;
            int mb = findMaxBit(U);
            while (mb+1) 
            {
                unsigned int cur = 1 << mb;
                if ((cur & N) == cur)
                {
                    //same 1
                    //check is need this bit to 1
                    if ((ans | a[mb]) < L && (ans|cur) <= U)
                    {
                        ans = ans | cur;
                    }
                }
                else
                {
                    //N的这位为0
                    if ((ans | cur) <= U)
                    {
                        ans = ans | cur;
                    }
                }
                --mb;
            }
            cout << ans << endl;
        }


    }

};


int main()
{

#ifndef ONLINE_JUDGE
    freopen("d://1.text", "r", stdin);
#endif // !ONLINE_JUDGE
    cc::solve();

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/shuiyonglewodezzzzz/p/10206650.html
今日推荐