zoukankan      html  css  js  c++  java
  • Codeforces 484A

    这题可以根据l, r 在二进制下的长度进行分类。

    l  的长度小于 r 的时候,有两种可能,一种是r 在二进制下是 1* 这种样子,故答案取 r ;

    一种是取答案为  (1LL << (rcnt - 1)) - 1 ,意思为比 r 小一位长度,也是 1* 这种样子的数。

    l 的长度等于 r 的时候,答案从 l 开始找 , 按位 与 1,同时要满足答案不大于 r  即可。

    source code (有参考):

    //#pragma comment(linker, "/STACK:16777216") //for c++ Compiler
    #include <stdio.h>
    #include <iostream>
    #include <cstring>
    #include <cmath>
    #include <stack>
    #include <queue>
    #include <vector>
    #include <algorithm>
    #define ll long long
    #define Max(a,b) (((a) > (b)) ? (a) : (b))
    #define Min(a,b) (((a) < (b)) ? (a) : (b))
    #define Abs(x) (((x) > 0) ? (x) : (-(x)))
    using namespace std;
    
    const int INF = 0x3f3f3f3f;
    
    int Cal(long long x){
        int ret = 0;
        while (x){
            ++ret;
            x >>= 1;
        }
        return ret;
    }
    
    int main(){
        int n;
        long long l, r, ret;
        cin >> n;
        while (n--){
            cin >> l >> r;
            int lcnt = Cal(l);
            int rcnt = Cal(r);
            if (lcnt < rcnt){   //for lcnt != rcnt, answer must like 1* to r
                if (r == (1LL << rcnt) - 1){
                    ret = r;
                }
                else{
                    ret = (1LL << (rcnt - 1)) - 1;
                }
            }
            else{               //for lcnt == rcnt, answer must be 1* and less than r
                for (int i = 0; i < rcnt; ++i){
                    if (((1LL << i) | l) <= r){
                        l |= (1LL << i);
                    }
                }
                ret = l;
            }
            cout << ret << endl;
        }
        return 0;
    }
  • 相关阅读:
    xna 添加一个精灵1
    【leetcode】705. 设计哈希集合
    【leetcode】1603. 设计停车系统
    【leetcode】设计有序流
    【leetcode】旅行终点站
    【leetcode】检测大写字母
    【leetcode】重复至少 K 次且长度为 M 的模式
    【leetcode】二叉树的直径
    【leetcode】公交站间的距离
    【leetcode】分糖果
  • 原文地址:https://www.cnblogs.com/wushuaiyi/p/4107821.html
Copyright © 2011-2022 走看看