简单并查集题目:hdu 1213“How Many Tables“

hdu 1213"How Many Tables"

题目:有n个人一起吃饭,有些人相互认识。认识的人想做坐在一起,不想跟陌生人坐。例如 A认识 B,B认识 C,那么A、B、D会坐在一张桌子上。

分析:一张桌子是一个集合,合并朋友关系,然后统计数量即可。下面是代码并查集的操作:

#include <bits/stdc++.h>
using namespace std;
const int maxn=1050;
int s[maxn];
void init_set(){//初始化 
	for(int i=1; i<=maxn; i++)
		s[i]=i; 
}
int find_set(int x){//查找 
	return x ==s[x]? x:find_set(s[x]);
	//是否被填充,是则下一个,否,此位置为待填充位置
}
int union_set(int x,int y){//合并 
	x =find_set(x);
	y =find_set(y);
	if(x!= y) s[x] =s[y];
}
int main(){
	int t,n,m,x,y;//m:多少组关系,n:有多少人 
	cin>>t;
	while(t--){
		cin>>n>>m;
		init_set();
		for(int i=1; i<=m;i++){
		  cin>>x>>y;
		  union_set(x,y); 
		}
		int ans=0;
		for(int i=1;i<=n;i++)
			if(s[i] ==i)
				ans++;
		cout<<ans<<endl; 
	}
	return 0;
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr顺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值