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

求连通分量

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

5 1
2 5

Sample Output
2
4

 

 1 # include <iostream>
 2 # include <cstdio>
 3 # include <cstring>
 4 # include <algorithm>
 5 # include <cmath>
 6 # include <queue>
 7 # define LL long long
 8 using namespace std ;
 9 
10 const int MAXN=1010;
11 int F[MAXN] ;
12 int find(int x)//找x的祖先结点
13 {
14     if(F[x]==x) return x;
15     return F[x]=find(F[x]);
16 }
17 void bing(int u,int v)
18 {
19     int t1=find(u);
20     int t2=find(v);
21     if(t1!=t2) //这两个点不在一个集合里
22       F[t1]=t2; //合到一个集合里
23 }
24 
25 
26 int main()
27 {
28     //freopen("in.txt","r",stdin) ;
29     int T ;
30     scanf("%d" , &T) ;
31     while(T--)
32     {
33         int n , m ;
34         int i ;
35         scanf("%d %d" , &n , &m) ;
36         for (i = 1 ; i<= n ; i++)
37            F[i] = i ;
38         int u , v ;
39         while(m--)
40         {
41             scanf("%d %d" , &u , &v) ;
42             bing(u,v) ;
43         }
44         int res = 0 ;
45         for (i = 1 ; i<= n ; i++)
46             if (F[i] == i)
47                res++ ;
48         printf("%d\n" , res) ;
49 
50     }
51 
52     return 0;
53 }
View Code

 

posted @ 2015-06-23 21:57  __Meng  阅读(342)  评论(0编辑  收藏  举报