^ & ^
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 507 Accepted Submission(s): 239
Problem Description
Bit operation is a common computing method in computer science ,Now we have two positive integers A and B ,Please find a positive integer C that minimize the value of the formula (A xor C) & (B xor C) .Sometimes we can find a lot of C to do this ,So you need to find the smallest C that meets the criteria .
For example ,Let’s say A is equal to 5 and B is equal to 3 ,we can choose C=1,3… ,so the answer we’re looking for C is equal to 1.
If the value of the expression is 0 when C=0, please print 1.
Input
The input file contains T test samples.(1<=T<=100)
The first line of input file is an integer T.
Then the T lines contains 2 positive integers, A and B, (1≤A,B<2^32)
Output
For each test case,you should output the answer and a line for each answer.
Sample Input
1
3 5
问题描述
给了两个正整数A,B,找一个正整数C,使得 (A xor C) & (B xor C) 的结果最小。这样的C可能不唯一,找出最小的那一个。
问题分析
记结果为ans=(A ^ C)&(B ^ C)。
由于^为位异或运算,&为位与运算。所以把A,B,C,ans转换为32位二进制数观察。
如
A
(
10
)
=
(
A
31
A
30
…
…
A
1
A
0
)
2
A_{(10)}=(A_{31}A_{30}……A_{1}A_{0})_2
A(10)=(A31A30……A1A0)2
那么对于每一位Ai,Bi,Ci,ansi有如下运算:
ansi=(Ai⊕Ci)(Bi⊕Ci),⊕为异或运算,x⊕y=xy’+yx’。化简后有:
a
n
s
i
=
A
i
B
i
C
i
′
+
A
i
′
B
i
′
C
i
ans_i=A_iB_iC_i^{'}+A_i^{'}B_i^{'}C_i
ansi=AiBiCi′+Ai′Bi′Ci
ansi与Ai,Bi,Ci的真值表
Ai | Bi | ansi |
---|---|---|
0 | 0 | C |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | C’ |
可见要使ans最小即ansi尽可能为0,且为使C尽可能小,Ci也尽可能为0.故当Ai=Bi=1时,Ci应该要为1,其它情况为0。
知道这些后,要找到A、B每一位,如果那一位为它们都为1,那么让C的这个位置也为1,否则为0。这样处理后,得到的结果基本上是答案,但注意可能结果为0,而题意中C为正整数,所以令C为1,因为1是比0大的最小正整数且只有一个位的值为1。
代码如下
#include<bits/stdc++.h>
using namespace std;
typedef unsigned int ui;
int main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
ui t,a,b,c,mask;
mask=1u<<31;
cin>>t;
while(t--){
cin>>a>>b;
c=0;
for(int i=31;i>=0;i--){
if((a&mask)&&(b&mask)) c+=1u<<i;
a<<=1;
b<<=1;
}
if(!c) c=1;
cout<<c<<endl;
}
return 0;
}