标签:
5
Huge input, scanf is recommended.
题目大意:给你一个图,求连接所有点的最短路径。
思路:Prim算法求图的最小生成树,模板题。
# include<stdio.h> # include<string.h> const int INF = 0xffffff0; const int MAXN = 110; int map[MAXN][MAXN],low[MAXN],vis[MAXN]; int n; int prim() { int i,j,pos,Min,result = 0; memset(vis,0,sizeof(vis)); vis[1] = 1; pos = 1; for(i = 1; i <= n; i++) if(i != pos) low[i] = map[pos][i]; for(i = 1; i < n; i++) { Min = INF; for(j = 1; j <= n; j++) { if(vis[j]==0 && Min > low[j]) { Min = low[j]; pos = j; } } result += Min; vis[pos] = 1; for(j = 1; j <= n; j++) { if(vis[j]==0 && low[j] > map[pos][j]) { low[j] = map[pos][j]; } } } return result; } int main() { int x,y,d; while(~scanf("%d",&n) && n) { memset(map,INF,sizeof(map)); for(int i = 1; i <= n*(n-1)/2; i++) { scanf("%d%d%d",&x,&y,&d); map[x][y] = map[y][x] = d; } printf("%d\n",prim()); } return 0; }
标签:
原文地址:http://blog.csdn.net/lianai911/article/details/42111349