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

hdu 1232 畅通工程(最小生成树)

时间:2014-08-06 17:25:01      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   for   

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

 

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
 
思路:最小生成树
bubuko.com,布布扣
 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<string.h>
 4 #include<stdlib.h>
 5 #include<math.h>
 6 #include<algorithm>
 7 #define LL long long
 8 #define mod 1e9 + 7
 9 const int M = 1005;
10 
11 using namespace std;
12 
13 struct node{
14     int x;
15     int y;
16 }a[M * M >> 1];
17 
18 int cun[M];
19 
20 int find(int x)
21 {
22     return cun[x] == x ? x : cun[x] = find(cun[x]);
23 }
24 
25 void shu(int x, int y)
26 {
27     int p = find(x);
28     int q = find(y);
29     cun[p] = q;
30 }
31 
32 int main()
33 {
34     int n, m;
35     while( cin >> n )
36     {
37         if(n == 0)
38             break;
39         cin >> m;
40         for(int i = 1; i <= m; ++i)
41             scanf("%d%d",&a[i].x,&a[i].y);
42         for(int i = 1; i <= n; ++i)
43             cun[i] = i;
44         int cnt = 1;
45         for(int i = 1; i <= m; ++i)
46         {
47             if(find(a[i].x) != find(a[i].y))
48             {
49                 shu(a[i].x,a[i].y);
50                 cnt++;
51             }
52         }
53         cout << n - cnt << endl;
54     }
55     return 0;
56 }
View Code

 

hdu 1232 畅通工程(最小生成树),布布扣,bubuko.com

hdu 1232 畅通工程(最小生成树)

标签:des   style   blog   http   color   os   io   for   

原文地址:http://www.cnblogs.com/Unico-liyang/p/3894489.html

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