标签:
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
3 5
#include <stdio.h> #include <string.h> #include <algorithm> #define inf 0x3f3f3f3f using namespace std; const int N = 1005; int map[N][N]; int vis[N]; int low[N]; int m,n; int prim(){ int i,j; memset(vis,0,sizeof(vis)); for(i=1;i<=n;i++){ if(i==1) low[i]=0; else low[i]=map[1][i]; } vis[1]=1; int ans=0; for(i=2;i<=n;i++){ int m=inf,t; for(j=1;j<=n;j++){ if(!vis[j]&&low[j]<m){ t=j; m=low[j]; } } vis[t]=1; ans=ans+m; for(j=1;j<=n;j++){ if(!vis[j]&&low[j]>map[t][j]) low[j]=map[t][j]; } } return ans; } int main(){ int i,j; while(~scanf("%d",&n)){ if(n==0) break; memset(map,inf,sizeof(map)); for(i=1;i<=n*(n-1)/2;i++){ int x,y,z; scanf("%d %d %d",&x,&y,&z); map[x][y]=min(map[x][y],z); map[y][x]=min(map[y][x],z); } printf("%d\n",prim()); } return 0; }
标签:
原文地址:http://blog.csdn.net/qq_27717967/article/details/51348025