HDU 1232 解题报告 并查集入门

24 篇文章 0 订阅

题目意思:

能连通的城市放置到同一个集合中,最后输出集合的个数减一即可。


#include <cstdio>
#define MMAX 1005

int father[MMAX];
int n, m;
void init()
{
	for (int i = 0; i < MMAX; ++i) father[i] = i;
}

int getfather(int n)
{
	/*递归写法, 在栈不爆的时候,效率较递归差
	int f, tmp;
	for (f = father[n]; f != father[f]; f = father[f]); //找出最远的祖先
	while (father[n] != f) {
		tmp = father[n];
		father[n] = f;
		n = tmp;
	}*/
	if (father[n] != n)
		father[n] = getfather(father[n]);
	return father[n];
}

void merge(int a, int b)
{
	int fa = getfather(a);
	int fb = getfather(b);
	if (fa != fb) {
		father[fb] = fa;
		n--;
	}
}

int main()
{
	//freopen("testdata/1232.txt", "r", stdin);
	int c1, c2;
	while (scanf("%d %d", &n, &m) != EOF && n) {
		 init();
		 for (int i = 0; i < m; ++i) {
		 	scanf("%d %d", &c1, &c2);
			merge(c1, c2);
		 }
		 printf("%d\n", n-1);
	}	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值