Claris and XOR

来源:互联网 发布:mac上可以玩什么网游 编辑:程序博客网 时间:2024/06/04 20:54
Claris and XOR
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 325 Accepted Submission(s): 132


Problem Description
Claris loves bitwise operations very much, especially XOR, because it has many beautiful features. He gets four positive integers a,b,c,d that satisfies a≤b and c≤d. He wants to choose two integers x,y that satisfies a≤x≤b and c≤y≤d, and maximize the value of x XOR y. But he doesn't know how to do it, so please tell him the maximum value of x XOR y.


Input
The first line contains an integer T(1≤T≤10,000)——The number of the test cases.
For each test case, the only line contains four integers a,b,c,d(1≤a,b,c,d≤1018). Between each two adjacent integers there is a white space separated.


Output
For each test case, the only line contains a integer that is the maximum value of x XOR y.


Sample Input

2
1 2 3 4
5 7 13 15



Sample Output

6
11

Hint

In the first test case, when and only when $x=2,y=4$, the value of $x~XOR~y$ is the maximum.

In the second test case, when and only when $x=5,y=14$ or $x=6,y=13$, the value of $x~XOR~y$ is the maximum

题解:本题通过枚举最高位来求解,我们从题目的极限数据来进行枚举,应该取到二进制的位60左右。通过来确定该位可不可以取固定值来确定x,y的大小,如果该位大于想b,d,那么x,y的该位只能是0,反之都小于则为1。如果恰好该位大于一个又小于一个,那么可使其异或结果恰为1.如果在想小于b而大于a,则该位可取1或0,y同理。如果该位可取任意,那么该为后面的都可取任意。因为x,y能取的值一定都是连续的一段,因此x,y的后len位都能取0111...1(len-1个1)和1000...0(len-1个0)(否则做不到从右向左数第len位都能取0,1)。也就是说,后len位的贡献一定能达到可能的上界111...1(len个1)。此时不必继续考虑后面的位


#include <iostream>#include <cstdio>#include <cstring>using namespace std;typedef long long ll;int t;ll a,b,c,d;int main(){    scanf("%d",&t);    while(t--){        scanf("%lld %lld %lld %lld",&a,&b,&c,&d);        ll sumx = 0;        ll sumy = 0;        for(int i=60;i>=0;i--){            ll temp = 1;            temp = temp<<i;//来比较当前最高位1000000....            if(temp+sumx <= b && temp+sumy <= d){//该位低于x和y的上限                if(temp+sumx<a && temp+sumy<c){//低于下限必须是1                    sumx += temp;                    sumy += temp;                }                else if(temp+sumx<a)//低于x的下限,x的该位必须是1                    sumx += temp;                else if(temp+sumy<c)//同理                    sumy += temp;                else   sumx += temp;//0,1都行            }            else if(temp+sumx <= b) sumx+=temp;//y是0,那么x就只能1            else if(temp+sumy <= d) sumy+=temp;//同理        }        ll ans = sumx^sumy;        printf("%lld\n",ans);    }}


0 0
原创粉丝点击