time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard output In order to celebrate Twice’s 5th anniversary, Tzuyu and Sana decided to play a game.
Tzuyu gave Sana two integers a and b and a really important quest.
In order to complete the quest, Sana has to output the smallest possible value of (a⊕x) + (b⊕x) for any given x, where ⊕ denotes the bitwise XOR operation.
Input Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤104). Description of the test cases follows.
The only line of each test case contains two integers a and b (1≤a,b≤109).
Output For each testcase, output the smallest possible value of the given expression.
Example inputCopy 6 6 12 4 9 59 832 28 14 4925 2912 1 1 outputCopy 10 13 891 18 6237 0 Note For the first test case Sana can choose x=4 and the value will be (6⊕4) + (12⊕4) = 2+8 = 10. It can be shown that this is the smallest possible value.
**思路:**本题是一个水题,首先要理解异或的含义,之后通过题目我们发现只有当两个数字的二进制表示下的同一位上的数字相同(都是0或者都是1)我们才有可能最终把答案里的这位数置为0,就是使整体变小,如果不相同的话这一位就无法避免,必须要在答案中加上。至此,题目已经非常清晰了。
**举例:**a=6,b=12,a的二进制表示就是110,b的二进制表示就是1100,他们跟一个相同的值x异或,只有当同一位上的数字一样时才能起到减小答案的作用,比如就可以取1110,1100,0110,0100四种,最终答案都是一样的。
***小提示:***最好把二进制每位数表示的十进制大小预先处理出来,防止超时。`
#include<bits/stdc++.h> using namespace std; typedef long long ll; int a,b; ll ans[40]; ll x[40],y[40]; ll qpow(ll x,ll y){ ll ans=1; while(y>0){ if(y%2!=0) { y--; ans*=x; } y/=2; x=x*x; } return ans; } int main() { int t; cin>>t; for(int i=0;i<=31;i++) { ans[i]=qpow(2,i); } while(t--) { cin>>a>>b; int flag1=0; int flag2=0; int id1=0,id2=0; for(int i=0;i<35;i++) { x[i]=y[i]=0; } for(int i=31;i>=0;i--) { if(a>=ans[i]) { if(flag1==0)id1=i; flag1=1; a-=ans[i]; x[i]=1; } if(b>=ans[i]) { if(flag2==0)id2=i; flag2=1; b-=ans[i]; y[i]=1; } } ll sum=0; for(int i=0;i<=max(id1,id2);i++) { if(x[i]!=y[i]) { sum+=ans[i]; } } printf("%lld\n",sum); } return 0; }