杭电ACM1213(并查集)

本文介绍了一道使用并查集解决社交宴请桌次问题的编程题,详细阐述了解题思路和AC代码,适用于算法与数据结构的学习。

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

题目大意:今天是Ignatius的生日,他要宴请一些客人,但是客人彼此之间并不是完全互相认识的,规定如果A认识B,且B认识C,则认为A,B,C互相认识,可以安排在同一桌,求需要安排的桌数。

解题思路:简单的并查集。

AC代码:

#include <iostream>
using namespace std;
int father[1005];
int getfather(int num)
{
	while(num!=father[num])
		num = father[num];
	return num;
}
void myunion(int x,int y)
{
	int rootx = getfather(x);
	int rooty = getfather(y);
	if(rootx!=rooty)father[rooty] = rootx;
}
int main()
{
	int t;
	int n,m;
	int a,b;
	int count;
//	int linked[1005];
	while(cin>>t)
	{
		while(t--)
		{
			count=0;
			cin>>n>>m;
			for(int i=1;i<=n;i++)
				father[i] = i;
			for(int i=1;i<=m;i++)
			{
				cin>>a>>b;
				myunion(a,b);
			}
			for(int i=1;i<=n;i++)
			{
				if(father[i]==i)count++;
			}
			cout<<count<<endl;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值