跳到正文

题解

题解:CF1774D Same Count One

wenhaoran11约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
获赞
1
题目
CF1774D

版本

  1. v1当前

题目大意

一共 TT 组测试数据,对于每组测试数据。给出 nn 组数,每组 mm 个数。其中数只有可能是 00 或 11 。可以在任意两组数中交换相同位置的数,求最少几次变换后,可以使每组数 11 的数量一致。输出变换次数与具体是如何变换的。如果无法满足题意,输出 −1-1 。

简单分析

什么样是输出 −1-1 的情况。设 nn 组数中一共有 aa 个 11 。则每组中1的数量为 a/na/n ,而如果 a/na/n 不是整数,说明无法每组平均分,输出 −1-1 即可。

深入探讨

剩余情况如何解决。设正常每组中应有 11 的数量为 tt ,而现在组中有 oo 个 11 。则如果 o>to>t 说明应该有一些 11 变为 00 ,而如果当前 ii 位置是 11 ,就统计起来。同理,如果 o<to<t ,说明应该有一些 00 应变为 11 ,而如果当前位置 ii 位置是 00 ,也统计起来。而最小次数用 lenlen 表示即可,在记录上文所说的两种情况中变动就好了。

主要代码。

C++
for(int i=1;i<=m;i++){
			int t1=0,t2=0;
			for(int j=1;j<=n;j++){
				if(cnt[j]>t&&p[j][i]==1) a[++t1]=j;
				if(cnt[j]<t&&p[j][i]==0) b[++t2]=j;
			}
			for(int j=1;j<=min(t1,t2);j++){
				ans[++len].x=b[j];
				ans[len].y=a[j];
				ans[len].z=i;
				cnt[a[j]]--;
				cnt[b[j]]++;
			}
		}
		cout<<len<<"\n";
		for(int i=1;i<=len;i++){
			cout<<ans[i].x<<' '<<ans[i].y<<' '<<ans[i].z<<"\n";
		}

整体代码。

C++
#include<bits/stdc++.h>
using namespace std;
const int N=200005;
int T,n,m,len,cnt[N],a[N],b[N];
vector<int> p[N];//统计每组1的数量
struct node{
	int x,y,z;
};
node ans[N];//统计题目所说的答案
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>T;
	while(T--){
		memset(a,0,sizeof a);
		memset(b,0,sizeof b);
		memset(cnt,0,sizeof cnt);
		int t=0;
		cin>>n>>m;
		for(int i=1;i<=n;i++){
			p[i].clear();
			p[i].push_back(0);
			for(int j=1;j<=m;j++){
				int x;
				cin>>x;
				p[i].push_back(x);
				t+=x;
				cnt[i]+=x;
			}
		}
		if(t%n!=0){//判断是否有解
			cout<<-1<<"\n";
			continue;
		}
		t/=n;
		len=0;
		for(int i=1;i<=m;i++){
			int t1=0,t2=0;
			for(int j=1;j<=n;j++){
				if(cnt[j]>t&&p[j][i]==1) a[++t1]=j;
				if(cnt[j]<t&&p[j][i]==0) b[++t2]=j;
			}
			for(int j=1;j<=min(t1,t2);j++){
				ans[++len].x=b[j];
				ans[len].y=a[j];
				ans[len].z=i;
				cnt[a[j]]--;
				cnt[b[j]]++;
			}
		}
		cout<<len<<"\n";
		for(int i=1;i<=len;i++){
			cout<<ans[i].x<<' '<<ans[i].y<<' '<<ans[i].z<<"\n";
		}
	}
	return 0;
}
原文