题目传送门
题目大意
给你一个长度为n的01数组,你可以删除其中不超过 n / 2 n/2 n/2位,使得数组满足 a 1 − a 2 + a 3 − a 4 + … = 0 a1−a2+a3−a4+…=0 a1−a2+a3−a4+…=0
思路
首先看到删除其中不超过 n / 2 n/2 n/2位这句话就应该想到删去其中的一半了,也就是删除01两者中最少的那个,删0留1的时候注意要保留偶数位的1
AC Code
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
#define endl '\n'
#define INF 0x3f3f3f3f
#define int long long
// #define TDS_ACM_LOCAL
const int N=2e5 +9;
int n, a[N];
void solve(){
cin>>n;
int ans1=0, ans0=0;
for(int i=1; i<=n; i++){
cin>>a[i];
if(a[i]==1) ans1++;
else ans0++;
}
if(ans1==n){
cout<<n<<endl;
while(ans1--) cout<<"1 ";
cout<<endl;
return ;
}
if(ans0==n){
cout<<n<<endl;
while(ans0--) cout<<"0 ";
cout<<endl;
return ;
}
if(ans1&1) ans1--, n--;
if(ans1>ans0){
cout<<n-ans0<<endl;
while(ans1--) cout<<"1 ";
cout<<endl;
return ;
}
if(ans1<=ans0){
cout<<n-ans1<<endl;
while(ans0--) cout<<"0 ";
cout<<endl;
return ;
}
return ;
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
#ifdef TDS_ACM_LOCAL
freopen("D:\\VS code\\.vscode\\testall\\in.txt", "r", stdin);
freopen("D:\\VS code\\.vscode\\testall\\out.txt", "w", stdout);
#endif
int T;
cin>>T;
while(T--) solve();
return 0;
}