题目描述
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most n2 elements (where n — length of array) in the way that alternating sum of the array will be equal 0 (i.e. a1−a2+a3−a4+…=0). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don’t have to be consecutive.
For example, if she has a=[1,0,1,0,0,0] and she removes 2nd and 4th elements, a will become equal [1,1,0,0] and its alternating sum is 1−1+0−0=0.
Help her!
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤103). Description of the test cases follows.
The first line of each test case contains a single integer n (2≤n≤103, n is even) — length of the array.
The second line contains n integers a1,a2,…,an (0≤ai≤1) — elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 103.
Output
For each test case, firstly, print k (n2≤k≤n) — number of elements that will remain after removing in the order they appear in a. Then, print this k numbers. Note that you should print the numbers themselves, not their indices.
We can show that an answer always exists. If there are several answers, you can output any of them.
Note
In the first and second cases, alternating sum of the array, obviously, equals 0.
In the third case, alternating sum of the array equals 1−1=0.
In the fourth case, alternating sum already equals 1−1+0−0=0, so we don’t have to remove anything.
样例
4
2
1 0
2
0 0
4
0 1 1 1
4
1 1 0 0
1
0
1
0
2
1 1
4
1 1 0 0
这就是一个比较复杂的模拟过程 ,当n等于2的时候 如果 0 和1 的个数存在有一个为0的话,那就可以一个不用删除 所以输出n输出数组元素即可,接下来用一个贪心的做法,因为最多删除是n/2个也就是你剩下的元素要大于等于n/2 所以如果0元素的个数大于n/2个我们就可以把0元素的个数全部输出出来,如果是1元素的个数大于n/2时 如果 1是偶数 可以全部输出出来,如果1是奇数 要想做到 符合条件,输出1的个数减1的个数的元素即可
#include<bits/stdc++.h>
const int maxn = 1e3+10;
int a[maxn],t,n;
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>t;
while(t--)
{
cin>>n;
int num0=0,num1=0;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++){
if(a[i]==0) num0++;
else num1++;
}
if(n==2)
{
if(num0==0||num1==0)
{
cout<<n<<endl;
for(int i=1;i<=n;i++){
cout<<a[i]<<' ';
}
cout<<endl;
}
else cout<<1<<endl<<0<<endl;
}
else if(num0>=n/2)
{
cout<<num0<<endl;
for(int i=1;i<=num0;i++)
{
cout<<0<<' ';
}
cout<<endl;
}
else{
if(num1%2==1)
{
cout<<num1-1<<endl;
for(int i=1;i<=num1-1;i++)
{
cout<<1<<' ';
}
cout<<endl;
}
else {
cout<<num1<<endl;
for(int i=1;i<=num1;i++)
{
cout<<1<<' ';
}
cout<<endl;
}
}
}
return 0;
}