hdu 1232 畅通工程

本文详细介绍了并查集算法的基本概念及其在Kruskal算法中的应用。通过具体实例讲解了如何利用并查集进行集合的查找与合并操作,并展示了如何通过路径压缩和权重压缩来优化并查集的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      赤裸裸的并查集,我还是习惯那位大牛写的方法,首先写出两个数组:father[i]=i和son[i]=1,然后依次查找元素并且使用路径压缩+权值压缩
#include<iostream>
#include<cstdio>
using namespace std;
#define MAX 1000
int son[MAX];
int father[MAX];
int find(int x)
{
	return x == father[x] ? x : find(father[x]);
}
void Union(int x,int y)
{
	int root1=find(x);
	int root2=find(y);
	   if(son[root1]>=son[root2])
	{
		father[root2]=root1;
		son[root1]+=son[root2];
	}
	else
	{
		father[root1]=root2;
		son[root2]=root1;
	}
}

int main()
{
//	freopen("1232.txt","r",stdin);
	int i,n,k,a,b;//n城市数目,k道路条数,a,b道路条数起始点
	while(1)
	{
		int count=-1;
		scanf("%d",&n);
		if(n==0)
			break;
		for(i=1;i<=n;i++)//初始化father[],son[]
		{
			father[i]=i;
			son[i]=1;
		}
		scanf("%d",&k);
		for(i=0;i<k;i++)
		{
			scanf("%d%d",&a,&b);
			  Union(a,b);
		}
		for(i=1;i<=n;i++)
		{
			if(father[i]==i)
			{
				count++;
			}
		}
		printf("%d\n",count);

	}
		
		return 0;
	
}
  在kruskal中正是运用的并查集的方法实现两个集合的合并

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值