poj 2524 求连通分量(并查集模板题)
求连通分量
Sample Input
10 9
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
10 4
2 3
4 5
4 8
5 8
0 0
Sample Output
Case 1: 1
Case 2: 7
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 = 50010; 11 int F[MAXN]; 12 int num[MAXN] ; 13 14 int find(int x)//找x的祖先结点 15 { 16 if(F[x]==x) return x; 17 return F[x]=find(F[x]); 18 } 19 void bing(int u,int v) //按秩合并 20 { 21 int x = find(u); 22 int y = find(v); 23 if(x == y) 24 return ; 25 if(num[x] >= num[y]) 26 { 27 F[y] = x; 28 num[x] += num[y]; 29 } 30 else 31 { 32 F[x] = y; 33 num[y] += num[x]; 34 } 35 } 36 int main() 37 { 38 //freopen("in.txt","r",stdin) ; 39 int n , m ; 40 int Case = 0 ; 41 while(scanf("%d %d", &n , &m) != EOF) 42 { 43 Case++ ; 44 if (n == 0 && m == 0) 45 break ; 46 47 int i ; 48 for(i = 1 ; i <= n ; i++) 49 { 50 F[i] = i ; 51 num[i] = 1 ; 52 } 53 int u , v ; 54 while(m--) 55 { 56 scanf("%d %d" , &u , &v) ; 57 bing(u , v) ; 58 59 } 60 int res = 0 ; 61 for(i = 1 ; i <= n ; i++) 62 if (F[i] == i) 63 res++ ; 64 printf("Case %d: %d\n" , Case , res) ; 65 } 66 return 0; 67 }