最小生成树。。。。
View Code
1 /* 2 prim 3 */ 4 #include<stdio.h> 5 #include<string.h> 6 #include<stdlib.h> 7 #include<algorithm> 8 #include<iostream> 9 #include<queue> 10 #include<vector> 11 #include<map> 12 #include<math.h> 13 typedef long long ll; 14 //typedef __int64 int64; 15 const int maxn = 105; 16 const int maxm = 1005; 17 const int inf = 0x7FFFFFFF; 18 const double pi = acos(-1.0); 19 const double eps = 1e-8; 20 using namespace std; 21 22 int mat[ maxn ][ maxn ]; 23 int vis[ maxn ],dis[ maxn ]; 24 25 void prim( int n ){ 26 for( int i=0;i<n;i++ ){ 27 vis[ i ] = 0; 28 dis[ i ] = mat[ 0 ][ i ]; 29 } 30 int res = 0; 31 vis[ 0 ] = 1; 32 for( int i=0;i<n;i++ ){ 33 int k,fmin; 34 fmin = inf; 35 for( int j=0;j<n;j++ ){ 36 if( vis[j]==0&&fmin>dis[ j ] ){ 37 fmin = dis[ j ]; 38 k = j; 39 } 40 } 41 if( fmin==inf ) break; 42 vis[ k ] = 1; 43 res += fmin; 44 for( int j=0;j<n;j++ ){ 45 if( vis[ j ]==0&&dis[ j ]>mat[ k ][ j ] ){ 46 dis[ j ] = mat[ k ][ j ]; 47 } 48 } 49 } 50 printf("%d\n",res); 51 } 52 53 int main(){ 54 int n; 55 char a[ 4 ],b[ 4 ]; 56 int k,cost; 57 while( scanf("%d",&n)==1,n ){ 58 //memset( mat,0,sizeof( mat ) ); 59 for( int i=0;i<n;i++ ) 60 for( int j=0;j<n;j++ ) 61 mat[i][j] = inf; 62 for( int i=0;i<n-1;i++ ){ 63 scanf("%s",a); 64 scanf("%d",&k); 65 while( k-- ){ 66 scanf("%s",b); 67 scanf("%d",&cost); 68 mat[ a[0]-'A' ][ b[0]-'A' ] = mat[ b[0]-'A' ][ a[0]-'A' ] = cost; 69 } 70 //prim( n ); 71 } 72 prim( n ); 73 } 74 return 0; 75 }