#628 (Div. 2)——D. Ehab the Xorcist

D. Ehab the Xorcist
 

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

Input

The only line contains 2 integers uu and v(0u,v1018)(0≤u,v≤1018).

Output

If there's no array that satisfies the condition, print "-1". Otherwise:

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

题意:找到一组数,使a1^a2^...^a^n=u && a1+a2+....+an=v

想法:我们知道相同的数进行异或等于零,所以u^x^x=u 这是要同时满足u+x+x=v,所以(v-u)/2 = x,这是在一般情况下,当然当(v-u)%2==1是,是没有结果的,输出“-1”,

           而在特殊情况下 在u==v&&u==0时我们可以输出0

                                     在u==v&&u!=0时我们知道u就是整个数组

                                     在u>v时,就是不可能了,因为不可能一个异或运算要比加法运算得到的结果还要大

         那两个数组的长度有没有可能呢?

在一般情况下我们知道(u^x^x)= u   (u+x+x)=v  现在要把他变成两个数 那我们就把这个公式分成两个部分

                                                              

那在实际上这是不等的,我们可以把异或运算想象成是不往上进位的运算 a+b=a^b+2(a&b)   加法等于本位得到的数加上数位上的进位数,通过&运算我们可以算出他的本位上应该进位的数,再乘以2就是实际进位上得到的数,那进行等价代换u+x=u^x+2(u&x)  那要满足上述的条件我们就需要u&x=0,如果满足这个条件我们就两个数就够了,反之就需要三个数

!!注意数据范围,要开long long

 1 #include <iostream>
 2 using namespace std;
 3 #define ll long long
 4 int main()
 5 {
 6     ll u,v;
 7     while(cin>>u>>v)
 8     {
 9 
10         if(u>v)
11         {
12             cout<<"-1"<<endl;
13         }
14         else if(u==v&&v==0)
15         {
16             cout<<"0"<<endl;
17         }
18         else if(u==v)
19         {
20             cout<<"1"<<endl<<u<<endl;
21         }
22         else
23         {
24 
25             ll x=(v-u)/2;
26             if((v-u)&1)
27             {
28                 cout<<"-1"<<endl;
29             }
30             else if((u&x)==0)
31             {
32                 cout<<"2"<<endl
33                     <<u+x<<" "<<x<<endl;
34             }
35             else
36             {
37                 cout<<"3"<<endl
38                     <<u<<" "<<x<<" "<<x<<endl;
39             }
40         }
41     }
42 
43     return 0;
44 }

猜你喜欢

转载自www.cnblogs.com/thief-of-book/p/12670307.html