HDU-1232畅通工程(并查集入门)

看这个博主讲的并查集入门看懂的,很有趣,一看就懂 传送门

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn=1005;
const int inf=0x3f3f3f3f;
int n,m,f[maxn];
int a[maxn];
int unionsearch(int root){
	int son=root;
	while(f[root]!=root){//祖先 
		root=f[root];
	}
	while(son!=root){
		son=f[son];
		f[son]=root;
	}
	return root;
}
int main()
{
	int a,b,root1,root2;
	while(scanf("%d%d",&n,&m),n){
		int  total=n-1;//初始化,若这个地方一条路都没修过,则最少需要 n-1条 
		for(int i=1;i<=n;i++){
			f[i]=i;
		}
		for(int i=0;i<m;i++){
			scanf("%d%d",&a,&b);
			root1=unionsearch(a);
			root2=unionsearch(b);
			if(root1!=root2){//表示新修的路a,b。若a,b是完全不相连的两条路,即根节点不一样,表示这条路已经修了,则需要修的路total-1。 
				f[root1]=root2;
				total--;
			}
		}
		printf("%d\n",total);
	}
    return 0;
}

还有一种输出方法,因为如果f[i]==i,表示该条路没有和其他路相连接,就要修一条路将其他路连接起来,因为本来就有一个根节点不需要再连接其他的根节点了,所以ans-1。

int ans=0;
		for(int i=1;i<=n;i++){
			if(f[i]==i)
			ans++;
		}
		printf("%d\n",ans-1);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值