#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int inf=0x7fffffff;
int n,m;
int map[110][110],hash[110],dis[110];
int prim()  
{     
       int sum=0;     
       dis[1]=0;    
       for(int i=1;i<=n;i++)     
       {         
              int pos,t=inf;         
              for(int j=1;j<=n;j++)         
              {
                    if(hash[j]==0)             
                    {                 
                          if(dis[j]<t)                 
                          {                     
                               t=dis[j];                   
                               pos=j;                
                          }             
                    }        
              }         
              hash[pos]=1;         
              if(pos==n) break;         
              for(int j=1;j<=n;j++)         
              {             
                   if(hash[j]==0)            
                   {                 
                         if(map[pos][j]!=inf&&map[pos][j]<dis[j])
                                dis[j]=map[pos][j];             
                   }                 
              }     
       }     
       for(int i=1;i<=n;i++)     
       {        
             sum+=dis[i];     
       }     
       return sum;//全省畅通的最小费用。  
}//最小生成树 int main() { int a,b,v; while(scanf("%d%d",&m,&n),n) { for(int i=1;i<=m;i++)//初始化 { dis[i]=inf; hash[i]=0; for(int j=1;j<=m;j++) { map[i][j]=inf; } } for(int i=1;i<=n;i++)//输入边对应的顶点及权值 { scanf("%d%d%d",&a,&b,&v); if(map[a][b]>v&&a!=b)//注意此处不能丢,因为有可能输入相同的边对应于不同的权值,找最小的输入 { map[a][b]=v; } } int res=prim(); printf("%d\n",res); } system("pause"); return 0; }
posted on 2011-05-25 17:07  枫叶飘泪  阅读(499)  评论(0编辑  收藏  举报