I did this for 40 points. still getting wrong ans for subtask 2. Help needed!!
#pragma GCC optimize "trapv"
#include<bits/stdc++.h>
#define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
using namespace std;
struct data
{
long long int num,ans;
};
bool compare (struct data a, struct data b)
{
if (a.ans!=b.ans)
return a.ans>b.ans;
else
return a.num<b.num;
}
signed main()
{
faster;
#ifndef ONLINE_JUDGE
freopen("ip.txt", "r", stdin);
freopen("op.txt", "w", stdout);
#endif
int t;cin>>t;
while(t--)
{
long long int a,b,l,r,j,c,temr,temc,count,cont;
cin>>a>>b>>l>>r;
c=a|b;
if (a==0 || b==0)
cout<<"0"<<endl;
else if (l==0 && c<=r)
cout<<c<<endl;
else if (l==0 && c>r)
{
temr=r,count=0;
while (temr!=0)
{
count++;
temr/=2;
}
long long int flag=1<<count;
c=c%flag;
int bitr[count],bitc[count];
if (c<=r)
cout<<c<<endl;
else if (c>r)
{
temr=r;
temc=c;
cont=count;
while (flag!=1)
{
flag/=2;
bitr[cont-1]=temr/flag;
bitc[cont-1]=temc/flag;
temr=temr%flag;
temc=temc%flag;
cont--;
}
vector <int> acc,notacc;
for (j=count-1;j>=0;j--)
{
if (bitr[j]==1 && bitc[j]==0)
break;
}
if (j<0) j=0;
for (int i=j;i<count;i++)
{
if (bitr[i]==0 && bitc[i]==1)
notacc.push_back(i);
if (notacc.size()>=1)
{
if (bitr[i]==1 && bitc[i]==1)
acc.push_back(i);
}
}
temc=c;
vector <struct data> s;
struct data temstruct;
for (int i=0;i<notacc.size();i++)
temc=temc-(1<<notacc[i]);
temstruct.num=temc;
temstruct.ans=(temc&a)*(temc*b);
s.push_back(temstruct);
for (int i=0;i<acc.size();i++)
{
temc=c;
temc-=(1<<acc[i]);
for (j=0;j<notacc.size();j++)
{
if (notacc[j]>acc[i])
temc-=(1<<notacc[j]);
}
temstruct.num=temc;
temstruct.ans=(temc&a)*(temc*b);
s.push_back(temstruct);
}
sort(s.begin(),s.end(),compare);
cout<<s[0].num<<endl;
}
}
}
}