hdu 1213 求连通分量(并查集模板题)

时间:2023-01-18 06:29:10

求连通分量

Sample Input
2 //T
5 3 //n m
1 2// u v
2 3
4 5

5 1
2 5

Sample Output
2
4

 # include <iostream>
# include <cstdio>
# include <cstring>
# include <algorithm>
# include <cmath>
# include <queue>
# define LL long long
using namespace std ; const int MAXN=;
int F[MAXN] ;
int find(int x)//找x的祖先结点
{
if(F[x]==x) return x;
return F[x]=find(F[x]);
}
void bing(int u,int v)
{
int t1=find(u);
int t2=find(v);
if(t1!=t2) //这两个点不在一个集合里
F[t1]=t2; //合到一个集合里
} int main()
{
//freopen("in.txt","r",stdin) ;
int T ;
scanf("%d" , &T) ;
while(T--)
{
int n , m ;
int i ;
scanf("%d %d" , &n , &m) ;
for (i = ; i<= n ; i++)
F[i] = i ;
int u , v ;
while(m--)
{
scanf("%d %d" , &u , &v) ;
bing(u,v) ;
}
int res = ;
for (i = ; i<= n ; i++)
if (F[i] == i)
res++ ;
printf("%d\n" , res) ; } return ;
}