还是畅通工程

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

Hint

Hint 
Huge input, scanf is recommended.
 
View Code
 1 #include<stdio.h>
2 #include<math.h>
3 #include<string.h>
4 #include<algorithm>
5 using namespace std;
6 struct node
7 {
8 int i, j , val;
9 }T[5000];
10 int set[105];
11 bool cmp( node A, node B )
12 {
13 return A.val < B.val;
14 }
15 void make_set()
16 {
17 for( int i = 1; i < 100; i++ )
18 set[i] = i;
19 }
20 int find( int x )
21 {
22 return set[x] == x? x: set[x] = find(set[x] );
23 }
24 int merge( int x, int y )
25 {
26 int x1 = find(x), y1 = find(y);
27 if( x1 != y1 )
28 set[x1] = y1;
29 }
30 int krusal( int count )
31 {
32 sort( T, T+count, cmp );
33 int a, b, c, result = 0;
34 for( int i = 0; i < count; i++ )
35 {
36 a = T[i].i;
37 b = T[i].j;
38 c = T[i].val;
39 if( find(a)!=find(b))
40 {
41 merge( a, b );
42 result += c;
43 }
44 }
45 return result;
46 }
47 int main()
48 {
49 int n;
50 while( scanf( "%d", &n )&&n )
51 {
52 int count = 0;
53 make_set();
54 for( int i =1; i <= (n*(n-1)/2); i++ )
55 {
56 scanf( "%d%d%d", &T[count].i, &T[count].j, &T[count].val );
57 count++;
58 }
59 printf( "%d\n",krusal( count ) );
60 }
61 }
原文地址:https://www.cnblogs.com/zsj576637357/p/2405010.html