A. Ahahahahahahahaha (构造+思维) Codeforces Round #669 (Div. 2)
原题链接: https://codeforces.com/contest/1407/problems
测试样例
input
4
2
1 0
2
0 0
4
0 1 1 1
4
1 1 0 0
output
1
0
1
0
2
1 1
4
1 1 0 0
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.
题意: 给你一个01数组,你可以通过删除最多 n / 2 n/2 n/2的元素。你要使得最后的数组定义的数组和(即奇位加,偶位减)为 0 0 0,请输出该数组。
解题思路: 这道题放在签到题,肯定是简单的。我们看:数组中只有 0 0 0和 1 1 1两种元素,那么是不是说明 0 0 0的数量或者 1 1 1的数量有一个 > = n / 2 >=n/2 >=n/2。 那么我们删除另一个数量小的是不是可以达到删除数量的限制。也就是说我们最后的数组要么只保留 1 1 1,要么只保留 0 0 0,这样达到的效果显而易见,我们数组定义的和为 0 0 0。当然,特殊情况在于只保留 1 1 1的时候,我们要使得奇偶位置上的数目相同,那么我们只要判断 1 1 1数量的奇偶性,如果为奇,就少输出一个。 (由于这个的限制,故如果 0 0 0和 1 1 1数量相等时,就应该以0为主导。)OK,具体看代码。
AC代码
/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h> //POJ不支持
#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair
using namespace std;
const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e5;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//
int t,n,a[maxn];
int cnt[2];//统计0和1的数目。
int main(){
//freopen("in.txt", "r", stdin);//提交的时候要注释掉
IOS;
while(cin>>t){
while(t--){
cin>>n;
cnt[0]=cnt[1]=0;//初始化。
rep(i,1,n){
cin>>a[i];
if(a[i])
cnt[1]++;
else
cnt[0]++;
}
//判断哪个大,相等时以0为主导。
if(cnt[0]>=cnt[1]){
cout<<cnt[0]<<endl;
rep(i,1,cnt[0])
cout<<0<<" ";
cout<<endl;
}
else{
if(cnt[1]%2)cnt[1]--;//由于我们要让数组规定和为0,故要确保奇偶位置数目相同。
cout<<cnt[1]<<endl;
rep(i,1,cnt[1])
cout<<1<<" ";
cout<<endl;
}
}
}
return 0;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)