HDU - 1232 畅通工程 并查集模板

某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路? 

Input测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。 
注意:两个城市之间可以有多条道路相通,也就是说 
3 3 
1 2 
1 2 
2 1 
这种输入也是合法的 
当N为0时,输入结束,该用例不被处理。 
Output对每个测试用例,在1行里输出最少还需要建设的道路数目。 
Sample Input

4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0

Sample Output

1
0
2
998


 
Huge input, scanf is recommended.

Hint

Hint

简化的题意就是有n个集合,最少合并几次才能成为一个集合。
答案当然是n-1次
附代码及自己封装好的并查集模板
 1 #include<iostream>
 2 using namespace std;
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<cstdlib>
 6 struct DSU{
 7     int *father;
 8     DSU(int n){//初始化一个节点数为n+1(编号0-n)的集合 
 9         father = new int[n+1];
10         /*把每一个节点设置为根节点,
11         也就是每个节点都是一个独立的集合*/
12         for(int i=0;i<=n;i++)
13             father[i]=i;
14     }
15     int Get_root(int x){//得到x节点的根节点 
16         if(father[x]==x)//如果某节点的父亲依然是这个节点
17             return x;//那么这个点就是根节点
18         //如果不是根节点 
19         int root = Get_root(father[x]);//那么递归地找它父亲的根节点 
20         father[x] = root;//路径压缩 
21         return root;//返回根节点的值 
22     }
23     void Union(int x,int y){//合并两个集合 
24         int root_x = Get_root(x);
25         int root_y = Get_root(y);
26         father[root_x] = root_y;//x的根节点接在y的树上
27     }
28     bool Judge(int x,int y){//判断两个节点是否是一个集合的
29          //等价于根节点是否相同 
30          return Get_root(x)==Get_root(y);    
31     }
32 };
33 int n,m;
34 DSU* s;
35 int main(){
36     while(true){
37         scanf("%d",&n);
38         if(n==0)
39             break;
40         scanf("%d",&m);
41         s = new DSU(n);//声明一个节点数为n+1的并查集 
42         for(int i=0;i<m;i++){
43             int p,q;
44             scanf("%d%d",&p,&q);
45             s->Union(p,q);//合并p,q 
46         }
47         int num = 0;//先有集合数量 
48         for(int i=1;i<=n;i++){//有几个集合就看有几个节点的父节点是本身 
49             if(s->Get_root(i) == i)
50                 ++num;
51         }    
52         printf("%d\n",num-1);//答案肯定为当前集合数-1 
53     }
54     return 0;
55 }

 



posted @ 2018-01-31 16:26  晓风微微  阅读(136)  评论(0编辑  收藏  举报