还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 29411 Accepted Submission(s): 13156
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
Huge input, scanf is recommended.
Hint
HintSource
解题思路:
直接裸裸的Kruskal 或者 Prim都能搞.
代码:
用kruskal搞的
1 # include<cstdio> 2 # include<iostream> 3 # include<fstream> 4 # include<algorithm> 5 # include<functional> 6 # include<cstring> 7 # include<string> 8 # include<cstdlib> 9 # include<iomanip> 10 # include<numeric> 11 # include<cctype> 12 # include<cmath> 13 # include<ctime> 14 # include<queue> 15 # include<stack> 16 # include<list> 17 # include<set> 18 # include<map> 19 20 using namespace std; 21 22 const double PI=4.0*atan(1.0); 23 24 typedef long long LL; 25 typedef unsigned long long ULL; 26 27 # define inf 999999999 28 # define MAX 123 29 30 int f[MAX]; 31 int n,m; 32 int sum; 33 34 struct edge 35 { 36 int u; 37 int v; 38 int w; 39 }e[10004]; 40 41 int cmp ( const struct edge & a,const struct edge & b ) 42 { 43 return a.w < b.w; 44 } 45 46 void input() 47 { 48 for ( int i = 1;i <= m;i++ ) 49 { 50 int t1,t2,t3; 51 scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].w); 52 } 53 } 54 55 int getf( int v ) 56 { 57 if ( v==f[v] ) 58 { 59 return v; 60 } 61 else 62 { 63 f[v] = getf(f[v]); 64 return f[v]; 65 } 66 } 67 68 int merge ( int v,int u ) 69 { 70 int t1 = getf(v); 71 int t2 = getf(u); 72 73 if ( t1!=t2 ) 74 { 75 f[t2] = t1;//t2的祖先是t1 76 return 1; 77 } 78 return 0; 79 } 80 81 void Kruskal() 82 { 83 int cnt = 0; 84 sort(e+1,e+m+1,cmp); 85 for ( int i = 1;i <= m;i++ ) 86 { 87 if ( merge( e[i].u,e[i].v ) ) 88 { 89 cnt++; 90 sum+=e[i].w; 91 } 92 if ( cnt==n-1) 93 return; 94 } 95 } 96 97 int main(void) 98 { 99 while ( scanf("%d",&n)!=EOF ) 100 { 101 if ( n==0 ) 102 break; 103 memset(e,0,sizeof(e)); 104 sum = 0; 105 m = (n-1)*n/2; 106 input(); 107 108 for ( int i = 1;i <= n;i++ ) 109 { 110 f[i] = i; 111 } 112 Kruskal(); 113 printf("%d ",sum); 114 } 115 116 return 0; 117 }
代码:
用Prim搞的