1325D - Ehab the Xorcist[思维+异或]
time limit per test | memory limit per test | input | output |
---|---|---|---|
1 seconds | 256 megabytes | standard input | standard output |
Description:
Given 2 2 2 integers u u u and v v v, find the shortest array such that bitwise-xor of its elements is u u u, and the sum of its elements is v v v.
Input
The only line contains 2 2 2 integers u u u and v ( 0 ≤ u , v ≤ 1 0 18 ) v (0≤u,v≤10^{18}) v(0≤u,v≤1018).
Output
If there’s no array that satisfies the condition, print “ − 1 -1 −1”. Otherwise:
The first line should contain one integer, n n n, representing the length of the desired array. The next line should contain n n n positive integers, the array itself. If there are multiple possible answers, print any.
One Example input
2 4
One Example output
2
3 1
One Example input
1 3
One Example output
3
1 1 1
Three Example input
8 5
Three Example output
-1
Four Example input
0 0
Four Example output
0
分析:
题意:
给两个数
u
,
v
u, v
u,v,
u
u
u表示
n
n
n个数的异或值,
v
v
v表示
n
n
n个数的和,问是否存在
n
n
n个数,使得满足上述情况(
n
n
n要尽可能小)
做法:
首先要考虑到当
u
>
v
u>v
u>v的时候,显然是不可能的
其次
n
n
n个数的异或值与
n
n
n个数的和应该满足奇偶性相同,即
(
v
−
u
)
%
2
=
=
0
(v - u) \% 2 == 0
(v−u)%2==0
如果不相同则也不存在,原因在于异或后每次相差的都是
2
x
2^x
2x
接下来是
u
=
=
v
u == v
u==v的情况,如果都为
0
0
0,则应该是
0
0
0个数
否则输出的就是
u
u
u
剩下的情况还要再分为两类
我们考虑将
v
−
u
v-u
v−u先拿出来,然后拆成均等的两份,即每份为
(
v
−
u
)
/
2
(v-u) / 2
(v−u)/2,显然这两个异或值为
0
0
0
在放个值为
u
u
u,那么就大功告成了
然鹅,然鹅
如果
(
(
u
+
x
)
⊕
x
)
=
=
u
((u+x) \oplus x) == u
((u+x)⊕x)==u的话,那么可以将
x
x
x与
u
u
u合并
也就是说一个数为
(
x
+
u
)
(x+u)
(x+u),另一个数为
x
x
x
比如说
u
=
100101
u = 100101
u=100101,
x
=
1010
x = 1010
x=1010,这样的情况就可以合并了
Code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
int main() {
ll u, v;
scanf("%lld%lld", &u, &v);
if(v < u || (v - u) & 1) {
puts("-1");
}else if(v == u) {
if(u == 0) puts("0");
else printf("1\n%lld\n", u);
}else{
ll x = (v - u) / 2;
if(((u+x) ^ x) == u)
printf("2\n%lld %lld\n", u + x, x);
else
printf("3\n%lld %lld %lld\n", u, x, x);
}
return 0;
}