HDU 1233 还是畅通工程

还是畅通工程

Time Limit: 2000ms
Memory Limit: 32768KB
This problem will be judged on  HDU. Original ID: 1233
64-bit integer IO format: %I64d      Java class name: Main
 
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
 

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
Huge input, scanf is recommended.

Source

 
解题:最小生成树
 
 1 #include <iostream>

 2 #include <cstdio>

 3 #include <cstring>

 4 #include <cmath>

 5 #include <algorithm>

 6 #include <climits>

 7 #include <vector>

 8 #include <queue>

 9 #include <cstdlib>

10 #include <string>

11 #include <set>

12 #include <stack>

13 #define LL long long

14 #define pii pair<int,int>

15 #define INF 0x3f3f3f3f

16 using namespace std;

17 struct arc{

18     int u,v,w;

19     arc(int x = 0,int y = 0,int z = 0){

20         u = x;

21         v = y;

22         w = z;

23     }

24 };

25 arc e[10000];

26 int n,m,uf[110];

27 bool cmp(const arc &x,const arc &y){

28     return x.w < y.w;

29 }

30 int Find(int x){

31     if(x != uf[x]) uf[x] = Find(uf[x]);

32     return uf[x];

33 }

34 int Kruskal(){

35     for(int i = 0; i <= n; i++) uf[i] = i;

36     sort(e,e+m,cmp);

37     int ans = 0;

38     for(int i = 0; i < m; i++){

39         int x = Find(e[i].u);

40         int y = Find(e[i].v);

41         if(x != y){

42             uf[x] = y;

43             ans += e[i].w;

44         }

45     }

46     return ans;

47 }

48 int main() {

49     int i,u,v,w;

50     while(scanf("%d",&n),n){

51         m = n*(n-1)/2;

52         for(i = 0; i < m; i++){

53             scanf("%d %d %d",&u,&v,&w);

54             e[i] = arc(u,v,w);

55         }

56         printf("%d\n",Kruskal());

57     }

58     return 0;

59 }
View Code

 

你可能感兴趣的:(HDU)