CodeForces-485C Bits(乱搞)

C. Bits
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Examples
input
3
1 2
2 4
1 10
output
1
3
7
Note

The binary representations of numbers from 1 to 10 are listed below:

110 = 12

210 = 102

310 = 112

410 = 1002

510 = 1012

610 = 1102

710 = 1112

810 = 10002

910 = 10012

1010 = 10102

题解:设L的二进制长度为len1,R的二进制长度为len2,分三种情况,①R的二进制全为1,直接输出r;②len2>len1且R的二进制不全为1,输出二进制长度为len2-1且二进制全为1的数;

③len2==len1,从高位到低位找到一个R的那一位是1,L的那一位是0的数位,再判断R在那一位之后是否全为1,如果是则把L的那一位之后且包括那一位全部变成1,如果不是则把

L的那一位之后的全部变成1,最后输出把L变成十进制再输出

#include<cstdio>
#include<queue>
#include<string.h>
#include<algorithm>
#include<stack>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define FIN freopen("in.txt","r",stdin)
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
int num1[66],num2[66];
int main(){
    int n;
    LL l,r;
   // FIN;
    scanf("%d",&n);
    while(n--){
        scanf("%I64d%I64d",&l,&r);
        if(l==r) {printf("%I64d\n",r);continue;}
        memset(num1,0,sizeof(num1));
        memset(num2,0,sizeof(num2));
        int len1=0,len2=0,cnt=0;
        LL tmp=r;
        while(l>0){
            num1[len1++]=(l&1);
            l>>=1;
        }
        while(r>0){
            cnt+=(r&1);
            num2[len2++]=(r&1);
            r>>=1;
        }
        if(cnt==len2) printf("%I64d\n",tmp);
        else if(len1<len2){
            printf("%I64d\n",(1ll<<(len2-1))-1ll);
        }
        else{
            int index=-1,flag=0;
            LL ans=0;
            for(int i=len1-1;i>=0;i--)
                if(num1[i]==0&&num2[i]==1) {index=i;flag=1;break;}
            cnt=0;
            for(int i=index;i>=0;i--) if(num2[i]) cnt++;
            if(cnt==index+1) for(int i=index;i>=0;i--) num1[i]=1;
            else for(int i=index-1;i>=0;i--) num1[i]=1;
            for(int i=0;i<len1;i++) if(num1[i]) ans+=(1ll<<i);
            printf("%I64d\n",ans);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值