HDU - 1213 How Many Tables (简单并查集)

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1213

题意:

T组数据, 1~n个数,m对关系,开始每个数一个组,每个组间出现关系边,则合并这两个组,求最后剩余组数

分析:

二维邻接矩阵搜索可以实现,但效率较低,开销较大

直接运用并查集,查找、合并,最后求并查集的根节点数

核心:

int Find(int x)
{
    if(x == parent[x])
        return x;
    else
        return parent[x] = find(parent[x]);
}


代码:

#include <stdio.h>

int nt, father[10000];
int find(int x)
{
	if(father[x]!=x) 
		father[x]=find(father[x]);
	return father[x];
}
int main()
{
	//int father[10000];
	int t;
	scanf("%d", &t);
	while(t--)
	{
		int n, m, i, j, x, y, a, b;
		scanf("%d%d", &n, &m);
		nt=n;
		for(i=1; i<=n;  i++)
		{
			father[i]=i;
		}
		for(i=0; i<m; i++)
		{
			scanf("%d%d", &x, &y);
			a=find(x); b=find(y);
			father[a]=b;
			if(a!=b) nt--;
		}
		printf("%d\n", nt);
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值