Codeforces Round #628 (Div. 2) D. Ehab the Xorcist 題解(思維+位運算)

原題鏈接:https://codeforces.com/contest/1325/problem/D


Given 2 integers u and v, find the shortest array such that bitwise-xor of its elements is u, and the sum of its elements is v.

Input
The only line contains 2 integers u and v (0u,v1018).(0≤u,v≤10^{18}).

Output
If there’s no array that satisfies the condition, print “-1”. Otherwise:

The first line should contain one integer, n, representing the length of the desired array. The next line should contain n positive integers, the array itself. If there are multiple possible answers, print any.

input

2 4

output

2
3 1

input

1 3

output

3
1 1 1

input

8 5

output

-1

input

0 0

output

0

Note
In the first sample, 3 ⊕ 1 = 2 and 3 + 1 = 4. There is no valid array of smaller length.

Notice that in the fourth sample the array is empty.


題意: 給出 u, v,求出一個長度最短的數組,其各元素的異或和等於 u,和等於 v 。

思路: 要分類討論。

  1. 首先要知道,答案數組所有元素必須小於 v,除非數組只有一個元素,因爲數組各元素的和要等於 v。如果 u > v,那麼 u 的高位爲 1 而小於 v 的任何數異或和都不會等於 u 。

  2. 如果 u == v,且 u、v 都不爲 0 ,那麼答案數組元素只有一個,即 u (v) 。

  3. 如果 u == v,且 u、v 都爲 0 ,那麼只能是空數組。

  4. 其他的情況就得來構造了。因爲兩個相同的數異或和等於 0 ,所以有 u ^ x ^ x = u ^ 0 = u,又因爲要使得 u+x+x = v,所以可以使得 x = (v - u) / 2 。

  5. 所以通過上一點可以知道,如果 v - u 是奇數也無解。

  6. 又因爲要使得數組最短,所以上面的情況構造的數組長度爲 3 ,那麼我們可以把 u 和 一個 x 合併,就變成了,u+x 和 x,也就是 (v+u) / 2 和 (v-u) / 2,然後判斷一下是否符合條件。不符合就輸出長度爲 3 的數組。

  7. 綜上所述,先把特判解決了,然後只要有解,就至少有長度爲 3 的數組,然後再判斷合併爲長度爲 2 是否符合條件。

  8. 要注意位運算的優先級比較低,所以儘量都加個括號,不然容易出錯。


參考博客:https://blog.csdn.net/JiangHxin/article/details/104875015

Code:

#include <iostream>
using namespace std;
typedef long long ll;
int main(){
    ll u,v;    cin>>u>>v;
    if(u>v || ((v-u)&1))
        cout<<-1<<endl;
    else if(u==v){
        if(!u)  cout<<0<<endl;
        else    cout<<1<<endl<<u<<endl;
    }
    else{
        ll x = (v-u)/2;
        if(((u+x)^x)==u && u+x+x==v)  cout<<2<<endl<<u+x<<' '<<x<<endl;
        else    cout<<3<<endl<<u<<' '<<x<<' '<<x<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章