Codeforces 76D

蛮有意思的一个关于二进制的题,建立在plus和xor的关系上的题,

由于 $A = X + Y, B = X ; mathrm{xor} ; Y$,那么 $A = B + ((X ;  mathrm{and} ;  Y) << 1)$。

因此 $X ; mathrm{and} ; Y = (A - B) >> 1$,然后同时根据 $X ; mathrm{xor} ; Y = B, X ; mathrm{and} ; Y = (A - B) >> 1$ 这两个条件,在二进制下一位一位的去分类讨论一下 $X$ 和 $Y$ 在那以为到底是 $0$ 还是 $1$。

记 $X$ 和 $Y$ 的每一位分别是 $x$ 和 $y$,讨论:$x ; mathrm{and} ; y = ; ?, x ; mathrm{xor} ; y = ; ?$

① $1 ; mathrm{and} ; 1 = 1, 1 ; mathrm{xor} ; 1 = 0$,

② $0 ; mathrm{and} ; 0 = 0, 0 ; mathrm{xor} ; 0 = 0$,这俩是固定的,没得选。

③ $1 ; mathrm{and} ; 0 = 0, 1 ; mathrm{xor} ; 0 = 1$,

④ $0 ; mathrm{and} ; 1 = 0, 0 ; mathrm{xor} ; 1 = 1$,这俩显然选④,让X更小。

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
 
    ull a, b;
    cin >> a >> b;
 
    if(a < b)  // A will not be less than B
    {
        cout << "-1";
        return 0;
    }
 
    ull delta = a - b;
    if((delta & 1) != 0)  // if A-B is not even number
    {
        cout << "-1";
        return 0;
    }
 
    ull x = 0, y = 0;
    delta >>= 1;  // now, delta = x and y
    ull k = 1;  // k = 1, 10, 100, 1000, ...
    while(true)
    {
        ull and_lp = delta & 1, xor_lp = b & 1;  // get last place
//        cout << xor_lp << " " << and_lp << endl;
        if(xor_lp == 0 && and_lp == 1)
            x |= k, y |= k;
        else if(xor_lp == 0 && and_lp == 0)
            ;  // do nothing
        else if(xor_lp == 1 && and_lp == 0)
            y |= k;
        else
        {
            cout << "-1";
            return 0;
        }
 
        if(delta == 0 && b == 0)
            break;
        else
            delta >>= 1, b >>= 1, k <<= 1;
    }
 
    cout << x << " " << y;
    return 0;
}
转载请注明出处:https://dilthey.cnblogs.com/
原文地址:https://www.cnblogs.com/dilthey/p/14811628.html