CodeForces484A——Bits(贪心算法)

时间:2023-03-09 00:39:43
CodeForces484A——Bits(贪心算法)

Bits

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 成立,且在[L,R)区间中为最优解。

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

Code:

 /*************************************************************************
> File Name: CF484A.cpp
> Author: Enumz
> Mail: 369372123@qq.com
> Created Time: 2014年11月06日 星期四 01时49分25秒
************************************************************************/ #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<list>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#include<cmath>
#include<bitset>
#include<climits>
#define MAXN 100000
#define LL long long
using namespace std;
int main()
{
LL a,b,ans;
int T,k;
cin>>T;
while (T--)
{
ans=;
cin>>a>>b;
int i;
bool flag=;
for (i=; i>=; i--)
{
if (flag)
{
ans+=1LL<<i;
continue;
}
if((a&(1LL<<i))==(b&(1LL<<i)))
{
if ((a&(1LL<<i))!=)
ans+=1LL<<i;
}
else
{
flag=;
k=i;
i++;
}
}
if (ans>b)
ans=ans^(1LL<<k);
cout<<ans<<endl;
}
return ;
}