一个和其它题解不同的做法。更复杂了。
思路
首先算出 和 的二进制表示,如果 长度不足,则高位补 。
为了方便叙述,这里使用 表示 的二进制表示从低位开始数的第 位(从 开始), 表示最终答案。
考虑从高到低枚举每一位,对于第位,如果:
- ,
只能取 。
这时候就会有人说了:“你说的是前面的上界全部顶满的情况,如果没有顶满, 就可以取 了。”
对于这个问题,一会就会说到。 - ,
同上, 只能取 。 - ,
有两种情况。 如果 取 ,则更低位一定可以全部取 ,否则继续向下看。
取两种方案的最大值即可。 - ,
只有上界顶满才会继续向下看,而这种情况在上界顶满的情况下是无解的,所以可以直接返回极小值。
同理,由于只有上界顶满才会继续向下看,所以不会出现前面说的问题。
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
vector<int> ans;
int DFS(int pos,const vector<int>& a,const vector<int>& b)
{
if (pos<0)
{
return 0;
}
if (a[pos]==0)
{
if (b[pos]==0)
{
int res=DFS(pos-1,a,b);
ans[pos]=0;
return res;
}
int res=DFS(pos-1,a,b);
if (pos>=res+1)
{
fill(ans.begin(),ans.begin()+pos,1);
ans[pos]=0;
}
else
{
ans[pos]=1;
}
return max(pos,res+1);
}
if (b[pos]==0)
{
return -1e18;
}
int res=DFS(pos-1,a,b);
ans[pos]=1;
return res+1;
}
int t,l,r;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin>>t;
while (t--)
{
cin>>l>>r;
if (l==0)
{
if (r>0)
{
l++;
}
else
{
cout<<"0\n";
continue;
}
}
vector<int> a,b;
int cnt1=0,cnt2=0;
while (l)
{
cnt1++;
a.push_back(l&1);
l>>=1;
}
while (r)
{
cnt2++;
b.push_back(r&1);
r>>=1;
}
while (cnt1<cnt2)
{
a.push_back(0);
cnt1++;
}
ans.clear();
ans.resize(a.size());
DFS(a.size()-1,a,b);
int sum=0;
for (int i=0;i<cnt1;i++)
{
sum+=(1ll<<i)*ans[i];
}
cout<<sum<<'\n';
}
return 0;
}总时间复杂度 ( 是因为可能出现每轮DFS时都先fill再DFS的情况),但是如果刻意优化的话是可以优化到 的。懒,不想写。