题意:。。。
策略:最最典型的prim算法。
代码:
#include<stdio.h> #include<string.h> #define INF 0x3f3f3f3f #define MAXN 105 int map[MAXN][MAXN], di[MAXN], vis[MAXN]; int n; int prim() { int i, j, min, pos; memset(vis, 0, sizeof(vis)); memset(di, 0, sizeof(di)); pos = 1; for(i = 1; i <= n; i ++){ di[i] = map[pos][i]; } int sum = 0; vis[1] = 1; for(i = 1; i < n; i ++){ min = INF; for(j = 1; j <= n; j ++){ if(!vis[j]&&min>di[j]){ min = di[j]; pos = j; } } sum += min; vis[pos] = 1; for(j = 1; j <= n; j ++){ if(!vis[j]&&di[j] > map[pos][j]){ //这里需要更新当前di与(dijkstra算法不一样)做的时候搞混了 di[j] = map[pos][j]; } } } return sum; } int main() { int i, j, a, b, c; while(scanf("%d", &n), n){ for(i = 1; i <= n; i ++){ for(j = 1; j <= n; j ++){ map[i][j] = i==j?0:INF; } } memset(map, 0, sizeof(map)); for(i = 0; i < n*(n-1)/2; i ++){ scanf("%d%d%d", &a, &b, &c); if(map[a][b]>c||!map[a][b]){ map[a][b] = map[b][a] = c; } } int ans = prim(); printf("%d\n", ans); } }
HDOJ 1233 还是畅通工程 【最小生成树】+【prim】,布布扣,bubuko.com
HDOJ 1233 还是畅通工程 【最小生成树】+【prim】
原文地址:http://blog.csdn.net/shengweisong/article/details/38518971