HDU 1233 还是畅通工程 (最小生成树)
还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 30542 Accepted Submission(s): 13670
Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
当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 <iostream> 2 #include <cstdio> 3 #include <string> 4 #include <queue> 5 #include <vector> 6 #include <map> 7 #include <algorithm> 8 #include <cstring> 9 #include <cctype> 10 #include <cstdlib> 11 #include <cmath> 12 #include <ctime> 13 using namespace std; 14 15 const int SIZE = 105; 16 int FATHER[SIZE],N,M,NUM; 17 int MAP[SIZE][SIZE]; 18 struct Node 19 { 20 int from,to,cost; 21 }G[SIZE * SIZE]; 22 23 void ini(void); 24 int find_father(int); 25 void unite(int,int); 26 bool same(int,int); 27 int kruskal(void); 28 bool comp(const Node &,const Node &); 29 int main(void) 30 { 31 while(scanf("%d",&N) && N) 32 { 33 ini(); 34 M = N * (N - 1) / 2; 35 for(int i = 0;i < M;i ++) 36 { 37 scanf("%d%d%d",&G[NUM].from,&G[NUM].to,&G[NUM].cost); 38 NUM ++; 39 } 40 sort(G,G + NUM,comp); 41 kruskal(); 42 } 43 44 return 0; 45 } 46 47 void ini(void) 48 { 49 NUM = 0; 50 for(int i = 1;i <= N;i ++) 51 FATHER[i] = i; 52 } 53 54 int find_father(int n) 55 { 56 if(FATHER[n] == n) 57 return n; 58 return FATHER[n] = find_father(FATHER[n]); 59 } 60 61 void unite(int x,int y) 62 { 63 x = find_father(x); 64 y = find_father(y); 65 66 if(x == y) 67 return ; 68 FATHER[x] = y; 69 } 70 71 bool same(int x,int y) 72 { 73 return find_father(x) == find_father(y); 74 } 75 76 bool comp(const Node & a,const Node & b) 77 { 78 return a.cost < b.cost; 79 } 80 81 int kruskal(void) 82 { 83 int count = 0,ans = 0; 84 85 for(int i = 0;i < NUM;i ++) 86 if(!same(G[i].from,G[i].to)) 87 { 88 unite(G[i].from,G[i].to); 89 count ++; 90 ans += G[i].cost; 91 if(count == N - 1) 92 break; 93 } 94 printf("%d\n",ans); 95 }