蓝桥 历届试题 合根植物

虽然思路很简单是裸的并查集,但是代码要注意细节,我在写的时候就忘了写判断语句 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