标签:des style blog io color os sp for 数据
3 2 1 2 1 1 3 1 1 0
2 0
#include<stdio.h> #include<string.h> #include<stdlib.h> #define MAXN 10000 #define inf 1<<28 int n, m; int mapp[MAXN][MAXN]; int vis[MAXN], dis[MAXN]; void init() { int i, j; for(i=1; i<=n; i++) { for(j=1; j<=n; j++) { mapp[i][j] = inf; } if(i==j) mapp[i][j] = 0; } } void prim() { int i, j, pos, ans=0, min; for(i=2; i<=n; i++) dis[i] = mapp[1][i]; vis[1] = 1; for(i=1; i<n; i++) { min = inf; for(j=2; j<=n; j++) { if(!vis[j] && dis[j]<min) { pos = j; min = dis[j]; } } vis[pos] = 1; ans += min; for(j=2; j<=n; j++) { if(!vis[j] && mapp[pos][j]<dis[j]) dis[j] = mapp[pos][j]; } } printf("%d\n", ans); } int main() { int i, j; int u, v, c; while(~scanf("%d%d", &n, &m)) { init(); memset(vis, 0, sizeof(vis)); memset(dis, 0, sizeof(dis)); for(i=0; i<m; i++) { scanf("%d%d%d", &u, &v, &c); if(mapp[u][v]>c)//判重边 { mapp[u][v] = c; mapp[v][u] = c; } } prim(); } }
标签:des style blog io color os sp for 数据
原文地址:http://www.cnblogs.com/6bing/p/4120013.html