POJ 1258 Agri-Net
题目大意如下:
农民John当了镇长,他要为小镇谋福利,就为小镇所有的农场铺设光缆链接,给定矩阵表示没两个农场之间的距离,求铺设光缆的最小成本。
Prim算法,代码如下:
#include <stdio.h> #include <string.h> const int M=505; int map1[M][M],n; #define typec int // type of cost const typec inf = 0x3f3f3f3f; // max of cost int vis[M]; typec lowc[M]; typec prim(typec cost[][M]) // vertex: 0 ~ n-1 { int i, j, p; typec minc, res = 0; memset(vis, 0, sizeof(vis)); vis[0] = 1; for (i=1; i<n; i++) { lowc[i] = cost[0][i]; } for (i=1; i<n; i++) { minc = inf; p = -1; for (j=0; j<n; j++) { if (0 == vis[j] && minc > lowc[j]) { minc = lowc[j]; p = j; } } res+=minc; vis[p] = 1; for (j=0; j<n; j++) { if (0 == vis[j] && lowc[j] > cost[p][j]) { lowc[j] = cost[p][j]; } } } return res; } int main() { int i,j; while(scanf("%d",&n)!=EOF) { for(i=0; i<n; i++) { for(j=0; j<n; j++) { scanf("%d",&map1[i][j]); } } printf("%d\n",prim(map1)); } return 0; }