120561I
https://ac.nowcoder.com/acm/contest/120561/I
(同样诡异的🔑)
主要是找规律。
令为
的二进制最高位,令
,则
1.若,则显然答案为
。
2.若,则答案为
,因为区间中含有
到
的所有数,通过和
做与操作能得到
到
间的所有数字。
3.若,那么同2,一定可以得到
到
的所有数。同时
可以构造到比
更小的下界(这个下界等于二进制下
从
开始的第一段连续
构成的数),只要能拼接上即为
,否则为
。
代码:
#include<bits/stdc++.h>
using namespace std;
int read(){
char ch=getchar();int x=0,f=1;
while(ch<'0'||ch>'9'){
if(ch=='-') f=-1;
ch=getchar();
}
while(ch<='9'&&ch>='0'){
x=(x<<1)+(x<<3)+(ch^48);
ch=getchar();
}
return x*f;
}
int highbit(int x){
for(int i=31;i>=0;i--){
if(x&(1<<i)){
return i;
}
}
return -1;
}
void work(){
int l=read(),r=read();
if(l==0){
printf("%d\n",r+1);
return;
}
int a=highbit(l),b=highbit(r);
if(a+1<b){
printf("%d\n",r+1);
return;
}
if(a==b){
puts("0");
return;
}
int res=0;
for(int i=31;i>=0;i--){
if(l&(1<<i)){
while(l&(1<<i)){
res+=(1<<i);
i--;
}
break;
}
}
int ma=r-(1<<b);
if(ma+1>=res){
printf("%d\n",r+1);
return;
}
printf("%d\n",ma+1);
}
int main(){
int t=read();
while(t--){
work();
}
return 0;
}