3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
3 ?
AC代码:
#include <cstdio> #include <cstring> #include <algorithm> #define INF 0x7f7f7f7f using namespace std; int map[105][105], vis[105], dis[105]; int n, m; int prim() { for(int i = 1; i<=m; i++) dis[i] = map[1][i]; dis[1] = 0; vis[1] = 1; int sum = 0, pos; for(int i=1; i<m; i++) { int tmp = INF; for(int j=1; j<=m; j++) { if(!vis[j] && dis[j] < tmp) { tmp = dis[j]; pos = j; } } if(tmp == INF) return 0; vis[pos] = 1; sum += tmp; for(int j = 1; j <= m; j++) if(!vis[j] && map[pos][j] < dis[j]) dis[j] = map[pos][j]; } return sum; } int main() { while(scanf("%d %d", &n, &m)==2 && n) { int x, y, z; memset(vis, 0, sizeof(vis)); memset(dis, 0x7f, sizeof(dis)); //这里还可以这样赋值!! 每个值的大小为0x7f7f7f7f!! memset(map, 0x7f, sizeof(map)); //这里还可以这样赋值!! 每个值的大小为0x7f7f7f7f!! for(int i=1; i<=n; i++) { scanf("%d %d %d", &x, &y, &z); map[x][y] = map[y][x] = z; } int ans = prim(); if(ans) printf("%d\n", ans); else printf("?\n"); } return 0; }
HDU - 1863 - 畅通工程 (最小生成树!!prim算法!!)
原文地址:http://blog.csdn.net/u014355480/article/details/42268677