编程语言
首页 > 编程语言> > 2019中国大学生程序设计竞赛(CCPC) - 网络选拔赛 (^ & ^)

2019中国大学生程序设计竞赛(CCPC) - 网络选拔赛 (^ & ^)

作者:互联网

2019中国大学生程序设计竞赛(CCPC) - 网络选拔赛(^ & ^)

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<232)

Output
For each test case,you should output the answer and a line for each answer.

Sample Input
1
3 5

Sample Output
1

给你a和b的值让你求出尽可能小的c来使得(A xor C) & (B xor C) 尽可能小

解题思路:

注意:题目给的如果答案是c=0的情况下,输出1…
可把我坑死了

总之就是四种情况
a: 0 1 1 0
b: 0 1 0 1

看不懂???接着往下看:
数组s1 数组s2分别存储a和b的二进制形式下一步我们一位位的找
当然如果a是8 b是3
二进制形式就是
1000
0011
就是位数不够前面补零就行了
如果当前我们从低位到高位找,如果s1对应的值为0 s2对应的值为0 如果我们找的c的二进制形式当前位数的值为1的话
0^1=1 0^1=1
那么我们求得1&1=1
如果我们另找的c的二进制形式当前位数的值为0的话
0^0=0 0^0=0
那么我们求得0&0=0
很显然我们让c的值=0使得公式的结果小
所以0 0所对应的情况是 0
如果s1对应的值为1 s2对应的值为1 如果我们找的c的二进制形式当前位数的值为0的话
0^1=1 0^1=1
那么我们求得1&1=1
那如果另c的值为1呢?
1^1=0 1^1=0
0&0=0
显然当我们找到s1的值为 1 s2的值为1 的话我们另c的二进制形式的当前位数的值为 1 所以1 1所对应的情况是 1
那么当s1的值为 0 s2的值为1 会怎么样呢
如果另c=1的话
0^1=1 1^1=0
1&0=0
那么另c=0会咋样呢
0^0=1 1^0=1
1&0=0
当c=1 c=0我们都能是这一位位数值变成0,题目要求c的之最小对吧,所以c的二进制位数的值尽量是0才能使c的最终值最小嘛
所以 0 1 对应的c的值为 0
同理 1 0 对应的c的值为 0

所以我们推出了下面的结论:(这里abc的值为二进制形式)
a 0 0 1 1
b 0 1 1 0
c 0 0 1 0
所以只有当a b 的二进制的值为1的时候c的值为1 其他情况下c的值为0
因为数据给的是2的32次方的数
所以加上long long int 就搞完了
代码如下:


#include<bits/stdc++.h>
#define ll long long
using namespace std;
char s1[1000025],s2[1000025];
ll a,b,c,d;
ll T;
int main()
{
    cin>>T;
    while(T--)
    {
        cin>>a>>b;
        ll len1=0;
        ll len2=0;
        while(a)
        {
            s1[len1++]=a%2;
            a/=2;
        }
        while(b)
        {
            s2[len2++]=b%2;
            b/=2;
        }
        ll k=0;
        ll ans=0;
        ll m=1;
        while(k<len1&&k<len2)
        {
            if(s1[k]==1&&s2[k]==1)
            {
                ans+=m;
            }
            m*=2;
            k++;
        }
        if(ans==0)
        {
            cout<<1<<endl;
        }
        else
        {
            cout<<ans<<endl;
        }
    }
    return 0;
}

标签:xor,二进制,s2,ll,CCPC,对应,2019,选拔赛,s1
来源: https://blog.csdn.net/qq_44145094/article/details/100113216