[CSP-S Simulation Test]: maximum or (math)

Topic Portal (internal title 141)


Input Format

  Input file contains several test cases, the first acts of a positive integer $ T $, indicates the number of data sets.
  Then $ T $ lines of two positive integers $ l, r $. Data guarantee $ l \ leqslant r $ established.


Output Format

  $ T $ output lines, each a positive integer, satisfying the condition of $ X, or the maximum Y $ operation, i.e. the output of $ \ max (x \ or \ y) $.


Sample

Sample input:

3
1 10
1023 1024
233 322

Sample output:

15
1023
511


Data range and tips

  For $ 40 \% $ data satisfy $ r \ leqslant 500 $.
  For $ 70 \% $ data satisfy $ r \ leqslant 10 ^ 6 $ .
  For $ 100 \% $ data satisfies $ 1 \ leqslant l \ leqslant r \ leqslant 10 ^ {18}, 1 \ leqslant T \ leqslant 1,000 $.


answer

First, the $ l $ and $ r $ are converted to binary.

If it is not the same as the number of bits in binary, each bit can be $ 1 $, then the answer must be $ 1 << R-1 $, where $ R $ is $ r $ binary digits.

If the number is equal, from high to low on a different site in the future can be $ 1 $, but in front of what can only be on what it is.

Time complexity: $ \ Theta (T \ times \ log r) $.

Expectations score: $ 100 $ points.

Actual score: $ 100 $ points.


Code time

#include<bits/stdc++.h>
using namespace std;
long long L,R,ans;
int l[100],r[100],tl,tr;
void get()
{
	tl=tr=ans=0;
	while(L){l[++tl]=(L&1);L>>=1LL;}
	while(R){r[++tr]=(R&1);R>>=1LL;}
}
int main()
{
	int T;scanf("%d",&T);
	while(T--)
	{
		scanf("%lld%lld",&L,&R);get();
		if(tl==tr)
		{
			int res;
			for(int i=tl;i;i--){if(l[i]!=r[i])break;res=i;}
			ans=(1LL<<(res-1))-1;
			for(int i=res;i<=tl;i++)if(l[i])ans+=(1LL<<(i-1));
		}
		else ans=(1LL<<tr)-1;
		printf("%lld\n",ans);
	}
	return 0;
}

rp ++

Guess you like

Origin www.cnblogs.com/wzc521/p/11837758.html