题目意思:
Ignatius邀请了许多朋友来庆祝生日,他有个安排,就是互相认识的朋友才能坐在一桌,桌子非常大足够容纳很多人,问,最少需要多少张桌子?
他还规定了,A认识B,B认识C,那么ABC互相认识。
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1213
主要算法:并查集。
注意:1,查,2,并。
#include<iostream>
#include<cstdio>
using namespace std;
int f[1100];
int n,m;
int find(int x){
// int r=f[x];
// while(r!=f[r])
// r=f[r];
// return r;
if(x!=f[x])return find(f[x]);
return x;
}
void merge(int a,int b){
int fx,fy;
fx=find(a);
fy=find(b);
if(fx!=fy)
f[fy]=fx;
//f[fx]=fy;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)f[i]=i;
for(int i=1;i<=m;i++){
int a,b;
scanf("%d%d",&a,&b);
merge(a,b);
}
int ans=0;
for(int i=1;i<=n;i++)
if(f[i]==i)ans++;
printf("%d\n",ans);
}
return 0;
}