传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1213
典型的并查集裸题
并差集的相关知识不懂的话可以关注前面的博客。
大致意思:
今天是伊格纳修斯的生日。他邀请了很多朋友。现在是晚餐时间。伊格纳修斯想知道他至少需要多少张桌子。你必须注意到并非所有的朋友都相互认识,所有的朋友都不想和陌生人呆在一起。
这个问题的一个重要规则是,如果我告诉你A知道B,B知道C,那意味着A,B,C彼此了解,所以他们可以留在一个表中。
例如:如果我告诉你A知道B,B知道C,D知道E,所以A,B,C可以留在一个表中,D,E必须留在另一个表中。所以Ignatius至少需要2张桌子。
题意很明确,让你找有多少不同的集合。?很简单吧~嘿嘿
Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.
Sample Input
2
5 3
1 2
2 3
4 5
5 1
2 5
Sample Output
2
4
#include<iostream>
#include<cstdio>
using namespace std;
int t;
int fa[1005];
int n,m;
//初始化
void init(){
for(int i=1;i<=n;i++)
fa[i]=i;
}
//查找父节点
int find(int x){
if(fa[x]==x)return x;
else return fa[x]=find(fa[x]);
}
//合并父节点,路径压缩
void unit(int x,int y){
x=find(x);
y=find(y);
if(x!=y)
fa[x]=y;
}
int main(){
cin>>t;
int a,b,ans;
while(t--){
scanf("%d%d",&n,&m);
ans=0;
init();
for(int i=1;i<=m;i++){
scanf("%d%d",&a,&b);
unit(a,b);
}
//看是否在同一个集合
for(int i=1;i<=n;i++)
{
if(fa[i]==i)
ans++;
}
printf("%d\n",ans);
}
return 0;
}