题目链接:
time limit per test
1 secondmemory limit per test
256 megabytesinput
standard inputoutput
standard outputLet'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
题意:
在[l,r]中找一个数字使得这个数的二进制的1数目最多,如果有多种答案就输出最小的那个;
思路:
跟上次一道hdu的题目相似,按二进制位贪心,并更新l和r,如果当前为一个为0一个为1,那么就知道后面为都可以取1,还要判断这一位是否可取1,如果都是0那么就下一位,如果都是1那么就更新答案和l,r再进行下一位;
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <bits/stdc++.h>
#include <stack>
#include <map>
using namespace std;
#define For(i,j,n) for(int i=j;i<=n;i++)
#define mst(ss,b) memset(ss,b,sizeof(ss));
typedef long long LL;
template<class T> void read(T&num) {
char CH; bool F=false;
for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar());
for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar());
F && (num=-num);
}
int stk[70], tp;
template<class T> inline void print(T p) {
if(!p) { puts("0"); return; }
while(p) stk[++ tp] = p%10, p/=10;
while(tp) putchar(stk[tp--] + '0');
putchar('
');
}
const LL mod=1e9+7;
const double PI=acos(-1.0);
const LL inf=1e18;
const int N=1e5+20;
const int maxn=4e3+220;
const double eps=1e-12;
int n;
LL ans=0;
LL solve(LL l,LL r,int pos)
{
int tl=((l>>pos)&1),tr=((r>>pos)&1);//cout<<l<<" "<<r<<" "<<pos<<" "<<tl<<" "<<tr<<endl;
if(tl==0&&tr==1)
{
if(pos==0)ans+=1;
else
{
if(r!=(1LL<<(pos+1))-1)ans+=(1LL<<pos)-1;
else ans+=r;
}
}
else if(tl==0&&tr==0&&pos)solve(l,r,pos-1);
else if(tl==1&&tr==1)
{
ans+=(1LL<<pos);
if(pos)solve(l-(1LL<<pos),r-(1LL<<pos),pos-1);
}
}
int main()
{
read(n);
LL l,r;
For(i,1,n)
{
ans=0;
read(l);read(r);
solve(l,r,63);
print(ans);
}
return 0;
}