#include <stdio.h> #include <string.h> #define INF 100000000 int map[101][101]; int dis[101]; int vis[101]; int n; long long ans = 0; void prim() { int i,j; int min,pos; memset(vis,0,sizeof(vis)); memset(dis,INF,sizeof(INF)); vis[1] = 1; dis[1] = 0; for(i = 1;i<=n;i++) { dis[i] = map[1][i]; } min = INF; for(i = 1;i<=n-1;i++) { min = INF; for(j = 1;j<=n;j++) { if(!vis[j] && dis[j]<min) { pos = j; min = dis[j]; } } vis[pos] = 1; ans = ans + min; for(j = 1;j<=n;j++) { if(!vis[j] && dis[j]>map[pos][j]) dis[j] = map[pos][j]; } } } int main() { int i,j; int u,v,w; while(scanf("%d",&n),n) { for(i = 1;i<=n;i++) { for(j = 1;j<=n;j++) { if(i == j) map[i][j] = 0; else map[i][j] = INF; } } for(i = 1;i<=(n*(n-1))/2;i++) { scanf("%d%d%d",&u,&v,&w); { if(map[u][v]>w) { map[u][v] = map[v][u] = w; } } } prim(); printf("%lld\n",ans); ans = 0; } }
还是畅通工程 -- prim算法
时间: 2024-10-11 21:44:16