CodeForces484A——Bits(贪心算法)
创始人
2024-04-11 13:56:44
0


Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer x.
You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and is maximum possible. If there are multiple such numbers find the smallest of them.
Input
The first line contains integer n — the number of queries (1 ≤ n ≤ 10000).
Each of the following n lines contain two integers li, ri — the arguments for the corresponding query (0 ≤ li ≤ ri ≤ 1018).
Output
For each query print the answer in a separate line.
Sample test(s)
Input
3
1 2
2 4
1 10
Output
1
3
7
题目大意:

    给定L,R,输出X,X为[L,R]中化为二进制之后一的个数最多的那个数,(同时存在多个解,输出最小的那个)。

解题思路:

    设L,R的从高位开始有t1位相同,那么根据常识,x的前t1位(从高位开始数)必然也与LR相同。又因为L<=R,那么t1+1位不同,必然是L为0,R为1。

    此时将x的t1+1位赋值为0,后面所有为都为1。那么求出的X: L<=x

    存在特殊情况:R换成二进制之后全部为1,所以要加一个判断。判断x在t1+1位为1的时候是否绝对大于R,绝对大于的话,就将t1+1赋值为0;反之,赋值为1。

Code:

 6  ************************************************************************/7 8 #include9 #include
10 #include
11 #include
12 #include
13 #include
14 #include
15 #include
16 #include
17 #include
18 #include
19 #include
20 #include
21 #include
22 #define MAXN 100000
23 #define LL long long
24 using namespace std;
25 int main()
26 {
27     LL a,b,ans;
28     int T,k;
29     cin>>T;
30     while (T--)
31     {
32         ans=0;
33         cin>>a>>b;
34         int i;
35         bool flag=0;
36         for (i=60; i>=0; i--)
37         {
38             if (flag)
39             {
40                 ans+=1LL<b)
56             ans=ans^(1LL< 

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...