HDU1213+并查集

简单的并查集

View Code
 1 /*
 2 并查集
 3 */
 4 #include<stdio.h>
 5 #include<string.h>
 6 #include<stdlib.h>
 7 #include<algorithm>
 8 #include<iostream>
 9 #include<queue>
10 //#include<map>
11 #include<math.h>
12 using namespace std;
13 typedef long long ll;
14 //typedef __int64 int64;
15 const int maxn = 1005;
16 const int inf = 0x7fffffff;
17 const double pi=acos(-1.0);
18 const double eps = 1e-8;
19 int fa[ maxn ];
20 void init( int n ){
21     for( int i=1;i<=n;i++ )
22         fa[ i ]=i;
23 }
24 int find( int x ){
25     if( fa[x]==x ) return x;
26     fa[x]=find( fa[x] );
27     return fa[x];
28 }
29 void union_xy( int x,int y ){
30     int fa_x,fa_y;
31     fa_x = find( x );
32     fa_y = find( y );
33     if( fa_x>fa_y )
34         fa[ fa_y ]=fa_x;
35     else 
36         fa[ fa_x ]=fa_y;
37 }        
38 int main(){
39     int ca;
40     scanf("%d",&ca);
41     while( ca-- ){
42         int n,m;
43         scanf("%d%d",&n,&m);
44         init( n );
45         int a,b;
46         while( m-- ){
47             scanf("%d%d",&a,&b);
48             union_xy( a,b );
49         }
50         int cnt=0;
51         for( int i=1;i<=n;i++ ){
52             if( fa[i]==i )
53                 cnt++;
54         }
55         printf("%d\n",cnt);
56     }
57     return 0;
58 }

 

posted @ 2013-03-20 20:16  xxx0624  阅读(264)  评论(0编辑  收藏  举报