杭电 1233 还是畅通工程 (最小生成树)

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
 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 int fa[100000];
 5 struct stu
 6 {
 7     int from,to;
 8     int al;
 9 }st[100000];
10 int find(int a)
11 {
12     int r=a;
13     while(r != fa[r])
14     {
15         r=fa[r];
16     }
17     return r;
18 }
19 bool cmp(stu a,stu b)
20 {
21     return a.al<b.al;
22 }
23 int main()
24 {
25     int n,m,i;
26     while(scanf("%d",&n) && n)
27     {
28         m=n*(n-1)/2;
29     
30         for(i = 1 ; i <= n ;i++)
31         {
32             fa[i]=i;
33         }
34         for(i = 0 ; i < m ; i++)
35         {
36             scanf("%d %d %d",&st[i].from,&st[i].to,&st[i].al);
37         }
38         sort(st,st+m,cmp);
39         int k=0;
40         int sum=0;
41         for(i = 0 ; i<m ;i++)
42         {
43             if(k == n-1) break;
44             if(find(st[i].from) != find(st[i].to))
45             {
46                 fa[find(st[i].from)]=find(st[i].to);        //根节点相连 
47                 sum+=st[i].al;
48                 ++k;
49             }
50         }
51             printf("%d
",sum);
52     }
53 }
        
 
Huge input, scanf is recommended.
——将来的你会感谢现在努力的自己。
原文地址:https://www.cnblogs.com/yexiaozi/p/5733644.html