HDU6702^&^

6 篇文章 0 订阅

^ & ^

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)=(A31A30A1A0)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^{&#x27;}+A_i^{&#x27;}B_i^{&#x27;}C_i ansi=AiBiCi+AiBiCi
ansi与Ai,Bi,Ci的真值表

AiBiansi
00C
010
100
11C’

可见要使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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值