uva-10718-貪心
阿新 • • 發佈:2019-01-02
題意:輸入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; usingstd::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; }