码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-23 22:54:22      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

求连通分量

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     while(x!=F[x])
15         x=F[x];
16      return x;
17 }
18 void bing(int u,int v)
19 {
20     int t1=find(u);
21     int t2=find(v);
22     if(t1!=t2) //这两个点不在一个集合里
23       F[t1]=t2; //合到一个集合里
24 }
25 
26 
27 int main()
28 {
29     //freopen("in.txt","r",stdin) ;
30     int T ;
31     scanf("%d" , &T) ;
32     while(T--)
33     {
34         int n , m ;
35         int i ;
36         scanf("%d %d" , &n , &m) ;
37         for (i = 1 ; i<= n ; i++)
38            F[i] = i ;
39         int u , v ;
40         while(m--)
41         {
42             scanf("%d %d" , &u , &v) ;
43             bing(u,v) ;
44         }
45         int res = 0 ;
46         for (i = 1 ; i<= n ; i++)
47             if (F[i] == i)
48                res++ ;
49         printf("%d\n" , res) ;
50 
51     }
52 
53     return 0;
54 }
View Code

 

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

标签:

原文地址:http://www.cnblogs.com/-Buff-/p/4596378.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!