CF76D Plus and xor 题解

· · 题解

CF76D Plus and xor 题解

简化题意

一道大水题……

给出两个正整数 A,B,使 X,Y 满足以下条件:

\begin{aligned} X+Y=A\\ X\oplus Y=B \\ \end{aligned} \right.

分析

这里
先科普一下异或(\oplus),也叫半加运算,就是加法竖式不进位一样。
举个“栗”子: 729+534729 \oplus 534

729_{10}=1011011001_2 534_{10}=1000010110_2

先看 729+534

\begin{aligned} & 729_{10}+534_{10} \\ =& 1011011001_2+1000010110_2 \\ =& 10011101111_2 \\ =& 1263_{10} \end{aligned}

让我们再看看 729 \oplus 534

\begin{aligned} & 729_{10}\oplus534_{10} \\ =& 1011011001_2\oplus 1000010110_2 \\ =& 11001111_2 \\ =& 207_{10} \end{aligned}

我们再把这两个结果对比一下:

我们发现加法所得的结果只会比异或的结果多一些二进制下的 1
异或是不进位的加法,因此 A-B 表示的就是 X+Y 的进位情况。
由于加法得到的进位情况会是异或的 2 倍。所有 (A-B)\div2XY 的共同都有的部分。所有 X 可以认为是 (A-B)\div2

代码

接下来附上你们最爱的完整代码:

#include<iostream>
using namespace std;
unsigned long long int A,B,X,Y;
//坑点,2^64-1,需要unsigned long long int!
int main()
{
  cin>>A>>B;//输入
  if(A<B||A-B&1)
  {         //无解
    cout<<-1<<endl;
  }
  else
  { 
    X=A-B>>1;
    Y=A-X;
    cout<<X<<' '<<Y<<endl;
  }
  return 0; //养成好习惯~
}

管理大大审核辛苦啦!