首页 > 其他 > 详细

蓝桥 历届试题 合根植物

时间:2020-06-20 13:44:19      阅读:71      评论:0      收藏:0      [点我收藏+]

虽然思路很简单是裸的并查集,但是代码要注意细节,我在写的时候就忘了写判断语句 if(af != bf) f[bf] = a;

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 1e6+50;
int n,m,t,f[maxn];
int getf(int x)
{
	if(f[x] == x) return x;
	f[x] = getf(f[x]);
	return f[x];
}
void merge(int a,int b){
	int af = getf(a);
	int bf = getf(b);
	if(af != bf) f[bf] = a; //就是这!!只有两个人属于不同首领才进行融合!!
}
int main()
{
	scanf("%d%d",&n,&m); 
	for(int i = 1; i <= n*m; i++) f[i] = i;
	scanf("%d",&t);
	for(int i = 1; i <= t; i++){
		int x,y;
		scanf("%d%d",&x,&y);
		merge(x,y);
	}
	int ans = 0;
	for(int i = 1; i <= n*m; i++) cout<<i<<" ";
	cout<<endl; 
	for(int i = 1; i <= n*m; i++){
		if(f[i] == i) ans++;
		cout<<f[i]<<" ";
	}
	cout<<ans<<endl;
	return 0;
}

总结:并查集在融合时的判断语句!在融合时的判断语句!在融合时的判断语句!重要的说三遍!!

蓝桥 历届试题 合根植物

原文:https://www.cnblogs.com/Beic233/p/13168227.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!