HDU——1213 How Many Tables(并查集的简单应用)

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

在这里插入图片描述
题意:你有n个朋友要来聚会,有m条朋友之间的信息,你的朋友不想和陌生人坐在一起,问你最少需要准备多少张桌子?

解题思路:此题为并查集的模板题,若你对并查集还不是很熟的话,指路一篇并查集详解的博客:https://blog.csdn.net/hzf0701/article/details/107597903

AC代码

/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h>	//POJ不支持

#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair

using namespace std;

const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e5;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll>  pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//

int t;//t组测试用例
int n,m;//n个朋友,m种关系。
int father[maxn];//对应的关系,father[i]表示i的最远的朋友编号。
int ans;//需要订的桌子。
int Find(int x){
	int r=x;
	while(r!=father[r]){
		r=father[r];
	}
	int i=x,j;
	while(father[i]!=r){
		j=father[i];
		father[i]=r;
		i=j;
	}
	return r;
}
void unite(int x,int y){
	int fx=Find(x),fy=Find(y);
	if(fx!=fy){
		father[fx]=fy;
		ans--;//需要订的桌子数减1.
	}
}
int main(){
	//freopen("in.txt", "r", stdin);//提交的时候要注释掉
	IOS;
	while(cin>>t){
		while(t--){
			cin>>n>>m;
			rep(i,1,n)
				father[i]=i;
			int u,v;
			ans=n;//假设最初谁也不认识谁,则需要n张桌子。
			while(m--){
				cin>>u>>v;
				unite(u,v);
			}
			cout<<ans<<endl;
		}
	}
	return 0;
}

posted @   unique_pursuit  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示