HDU ACM 1232 畅通工程(并查集)

http://acm.hdu.edu.cn/showproblem.php?pid=1232

题意:不好说,自己看.

基本上根据并查集模版写出代码,只是作出简单的调用和在函数Union()中增加了道路数量的计算.

View Code
 1 #include <iostream>
 2 using namespace std;
 3 const int MAX = 1000 + 100;
 4 int father[MAX];
 5 int rank1[MAX];
 6 int sign[MAX];
 7 int step;
 8 void Make_Set(int x)//初始化
 9 {
10     father[x] = x;
11     rank1[x] = 0;
12 }
13 
14 int Find_Set(int x)//找根节点
15 {
16     int i=0;
17     while(father[x] != x)
18     {
19         sign[i++] = x;
20         x = father[x];
21     }
22     for(i;i>=1;i--)
23     {
24         father[sign[i-1]] = x;
25     }
26     return x;
27 }
28 
29 
30 void Union(int x,int y)//合并
31 {
32     x = Find_Set(x);
33     y = Find_Set(y);
34     if(x == y)
35     {
36         return;
37     }
38     step ++;//计算步数
39     if(rank1[x] > rank1[y])
40     {
41         father[y] = x;
42     }
43     else if(rank1[x] < rank1[y])
44     {
45         father[x] = y;
46     }
47     else if(rank1[x] ==rank1[y]) 
48     {
49         father[x] = y;           
50         rank1[y]++;             
51     }
52 }
53 
54 int main()
55 {
56     int n,m;
57     while(cin>>n,n)
58     {
59         cin>>m;
60         step =0;
61         int i;
62         for(i=1;i<=n;i++)
63         {
64             Make_Set(i);
65         }
66         for(i=1;i<=m;i++)
67         {
68             int a,b;
69             cin>>a>>b;
70             Union(a,b);
71         }
72         cout<<n-step-1<<endl;
73     }
74     return 0;
75 }

 

posted @ 2012-08-25 16:18  zx雄  阅读(290)  评论(0编辑  收藏  举报