题目网址:
http://codeup.cn/problem.php?cid=100000985&pid=0
1 /** 2 普里姆算法构造最小生成树 3 */ 4 #include <stdio.h> 5 #define N 105 6 #define INF 60000 7 int G[N][N],n; 8 typedef struct { 9 int dist; 10 int data; 11 }Closedge; 12 int ans; 13 void prim(int s){///从s结点查找 14 int flag[N];///标记是否被选中 15 Closedge closedge[N]; 16 for(int i = 0; i < N; i++) { 17 flag[i] = 0; 18 closedge[i].dist = G[s][i]; 19 closedge[i].data = s; 20 } 21 int m = 0,min; 22 flag[s] = 1; 23 while(m < n - 1){///加n-1个点 24 min = 0; 25 ///选出最小的那个 26 for(int i = 0; i < n; i++){ 27 if(closedge[min].dist > closedge[i].dist) 28 min = i; 29 } 30 ///入选min点 31 flag[min] = 1; 32 closedge[min].dist = INF; 33 ans += G[closedge[min].data][min]; 34 ///更新closedge数组 35 for(int j = 0; j < n; j++) 36 ///min与j直接相连 37 ///j点是没有入选的点 38 ///结点min到结点j < closeage.[data] 39 if(G[min][j] < closedge[j].dist && G[min][j]!=0 && !flag[j]){ 40 closedge[j].dist = G[min][j]; 41 closedge[j].data = min; 42 } 43 m++; 44 } 45 } 46 int main(void){ 47 while(scanf("%d",&n) != EOF){ 48 for(int i = 0; i < n; i++) 49 for(int j = 0; j < n; j++){ 50 scanf("%d",&G[i][j]); 51 if(G[i][j] == 0) 52 G[i][j] = INF; 53 } 54 ans = 0; 55 prim(0); 56 printf("%d\n",ans); 57 } 58 return 0; 59 }
原文:http://www.cnblogs.com/yfs123456/p/5740085.html