【CodeForces - 76D】Plus and xor(位運算-異或)
Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions in the operands are different.
For example, if X = 10910 = 11011012, Y = 4110 = 1010012, then:
X xor Y = 6810 = 10001002.
Write a program, which takes two non-negative integers A and B as an input and finds two non-negative integers X and Y, which satisfy the following conditions:
- A = X + Y
- B = X xor Y, where xor is bitwise exclusive or.
- X is the smallest number among all numbers for which the first two conditions are true.
Input
The first line contains integer number A and the second line contains integer number B
Output
The only output line should contain two integer non-negative numbers X and Y. Print the only number -1 if there is no answer.
Examples
Input
142 76
Output
33 109
題意:
給出兩整數A,B,要求找到X,Y滿足以下三個條件:
1.A=X+Y
2.B=X xor Y2其中xor表示異或運算
3.X是所有滿足前兩個條件中最小的
思路:
異或是不進位的加法,X和Y做異或運算,那麼,他們在同一個 位置的1會變成0,而其他一個1一個0的位置,則會變成1,因此做異或運算會比加法運算少2倍的相同位置的1的值,因此的值就是X和Y相同的部分,而X要求最小並且又必須要有相同部分,因此X可以取得最小就可以是,兩者的相同部分,其他的都由Y來提供。
再看不成立的條件,首先當A小於B時是不成立的,因為異或是不進位的加法如果兩個數沒有1在同一個位置上,那麼異或的值會和加法值相同,否則會有1變為0,異或的結果會變小。其次A-B是奇數的時候也是不成立的,由上面分析我們可以得出,A-B必定是偶數。
因為這道題的資料到了-1超過longlong的取值範圍,而在unsigned long long範圍內,因此可以用unsigned long long。
longlong取值範圍為-2^63到2^63-1,大概為9x10^18這麼多。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<set>
#include<iostream>
#include<map>
#include<stack>
#include<cmath>
#include<algorithm>
#define ll long long
#define mod 1000000007
#define eps 1e-8
using namespace std;
int main()
{
unsigned ll a,b;
cin>>a>>b;
unsigned ll tt,y,x;
tt=a-b;
if(b>a||tt&1)
{
printf("-1\n");
return 0;
}
x=tt>>1;
y=a-x;
cout<<x<<" "<<y<<endl;
return 0;
}