HDU-1233 还是畅通工程

Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
 

 

Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
 

 

Output
对每个测试用例,在1行里输出最小的公路总长度。
 

 

Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
 

 

Sample Output
3
5
 
 
 
 
模板如下
AC代码:(经供参考)
 
 1 #include<cstdio>
 2 #include<algorithm>
 3 
 4 using namespace std;
 5 
 6 int f[101];
 7 
 8 typedef struct e
 9 {
10     int a,b,w;
11 }eg;
12 eg e[5000];
13 
14 int cmp(eg x,eg y)
15 {
16     if(x.w<y.w)
17         return 1;
18     return 0;
19 }
20 
21 int find_set(int x)
22 {
23     if(x!=f[x])
24         f[x]=find_set(f[x]);///找到头
25 
26     return f[x];
27 }
28 
29 int main()
30 {
31     int n,m,z,x,y,i;
32 
33     while(scanf("%d",&n)&&n)
34     {
35         for(i=0;i<=n;i++)
36             f[i]=i;
37 
38         m=0;
39         z=n*(n-1)/2;
40 
41         for(i=0;i<z;i++)
42             scanf("%d%d%d",&e[i].a,&e[i].b,&e[i].w);
43         
44 
45         sort(e,e+z,cmp);
46 
47         for(i=0;i<z;i++)
48         { 
49             x=find_set(e[i].a);
50             y=find_set(e[i].b);
51 
52             if(x!=y)
53             {
54                 f[y]=x;
55                 m+=e[i].w;
56             }
57         }
58         printf("%d\n",m);
59     }
60     return 0;
61 }
View Code

 

自己必须要再敲一遍

1 #include<cstdio>
 2 #include<algorithm>
 3 
 4 using namespace std;
 5 
 6 int p[110];
 7 
 8 struct data
 9 {
10     int x, y, money;
11 }v[5100];
12 
13 int cmp(data a, data b)
14 {
15     return a.money < b.money;
16 }
17 
18 int Find(int x)
19 {
20     if (x != p[x])
21         p[x] = Find(p[x]);
22 
23     return p[x];
24 }
25 
26 int main()
27 {
28     int n;
29 
30     while(scanf ("%d", &n), n != 0)
31     {
32 
33         int i, z = n*(n-1)/2;
34 
35         for (i = 1; i <= n; i++)
36             p[i] = i;
37 
38         for (i = 0; i < z; i++)
39             scanf ("%d %d %d", &v[i].x, &v[i].y, &v[i].money);
40 
41         sort(v, v+z, cmp);
42 
43         int a, b, num = 0;
44 
45         for (i = 0; i < z; i++)
46         {
47             a = Find(v[i].x);
48             b = Find(v[i].y);
49 
50             if (a != b)
51             {
52                 p[b] = a;
53                 num += v[i].money;
54             }
55         }
56 
57         printf("%d\n", num);
58 
59     }
60     return 0;
61 }
View Code

 

 

posted @ 2016-08-08 16:30  劉小佳  阅读(152)  评论(0编辑  收藏  举报