标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 29411 Accepted Submission(s): 13156
解题思路:
直接裸裸的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\n",sum); 114 } 115 116 return 0; 117 }
代码:
用Prim搞的
HDU 1233 还是畅通工程 ( Kruskal或Prim)
标签:
原文地址:http://www.cnblogs.com/wikioibai/p/4436481.html