CodeForces Good Bye 2019——C. Make Good(异或的应用)

题目传送门:https://codeforces.com/contest/1270/problem/C

题目内容

Let’s call an array a1,a2,…,am of nonnegative integer numbers good if a1+a2+⋯+am=2⋅(a1⊕a2⊕⋯⊕am), where ⊕ denotes the bitwise XOR operation.

For example, array [1,2,3,6] is good, as 1+2+3+6=12=2⋅6=2⋅(1⊕2⊕3⊕6). At the same time, array [1,2,1,3] isn’t good, as 1+2+1+3=7≠2⋅1=2⋅(1⊕2⊕1⊕3).

You are given an array of length n: a1,a2,…,an. Append at most 3 elements to it to make it good. Appended elements don’t have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don’t have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.

Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤10000). The description of the test cases follows.

The first line of each test case contains a single integer n (1≤n≤105) — the size of the array.

The second line of each test case contains n integers a1,a2,…,an (0≤ai≤109) — the elements of the array.

It is guaranteed that the sum of n over all test cases does not exceed 105.

Output
For each test case, output two lines.

In the first line, output a single integer s (0≤s≤3) — the number of elements you want to append.

In the second line, output s integers b1,…,bs (0≤bi≤1018) — the elements you want to append to the array.

If there are different solutions, you are allowed to output any of them.

Example
input
3
4
1 2 3 6
1
8
2
1 1
output

2
4 4
3
2 6 2
Note
In the first test case of the example, the sum of all numbers is 12, and their ⊕ is 6, so the condition is already satisfied.

In the second test case of the example, after adding 4,4, the array becomes [8,4,4]. The sum of numbers in it is 16, ⊕ of numbers in it is 8.

题目大意

有一些数字,想办法添加几个数字,使得这几个数字的和等于两倍的这几个数字的异或。

题目分析

由异或的性质(相同为0,不同为1)可以知道,假设原来只有两个数字a和b。向其中添加两个新的数字a^b , a+b+a^b。则新的数组变为四个数字,这四个数字的和为:a +b+a^b +a+b +a^b =2*(a+b+a^b)。这四个数字的异或为a ^ b^(a ^ b) ^ (a+b+a ^ b)=0^(a+b+ a^b)=a+b+a ^b。正好是其和的二分之一,对于多个数字,此结果仍成立,请读者自行举例验证。所以,我们要做的就是先判断是否需要补充数字,如果需要的话,就补充两个数字,分别是当前所有数字的异或值,和当前所有数字之和+当前所有数字的异或值。

AC代码

#include
#include
#include
#include
#include
#define PI 3.1415926
typedef long long ll;
using namespace std;
int main()
{
	int t=0;
	cin>>t;
	static ll  a[100010]={0};
	while(t--)
	{
		ll  n=0;
		ll  x=0,y=0;
		scanf("%lld",&n);
		for(int i=0;i<n;i++)
		{
			scanf("%lld",&a[i]);
		}
		for(int i=0;i<n;i++)
		{
			x+=a[i];//所有数字的和
			y^=a[i];//所有数字的异或值
		}
		if(x==2*y)
		cout<<0<<endl<<" "<<endl;
		else
		cout<<2<<endl<<y<<" "<<x+y<<endl;
	} 
	return 0;
}

你可能感兴趣的:(ACM)