3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
3 5
1 #include <iostream>
2 #include <stdio.h>
3 #include <string.h>
4 using namespace std;
5 #define MAXN 110
6 #define UPPERDIS 9999999
7 int cost[MAXN][MAXN];
8 int n;
9 //普里姆算法模板
10 int lowcost[MAXN],closest[MAXN];
11 int prim(int v0)
12 {
13 int i,j,mindis,minone;
14 int ans = 0;/*用来记录最小生成树的总长度*/
15 /*各点距离初始化*/
16 for(i = 0;i < n;i++)
17 {
18 lowcost[i] = cost[v0][i];
19 closest[i] = v0;
20 }
21 for(i = 0;i < n-1;i++)
22 {
23 mindis = UPPERDIS;
24 for(j = 0;j < n;j++)
25 if(lowcost[j] && mindis > lowcost[j])
26 {
27 mindis = lowcost[j];
28 minone = j;
29 }
30 /*将找到的最近点加入最小生成树*/
31 ans += lowcost[minone];
32 lowcost[minone] = 0;
33 /*修正其他点到最小生成树的距离*/
34 for(j = 0;j < n;j++)
35 if(cost[j][minone] < lowcost[j])
36 {
37 lowcost[j] = cost[j][minone];
38 closest[j] = minone;
39 }
40 }
41 return ans;
42 }
43 int main()
44 {
45 while(scanf("%d",&n)!=EOF){
46 if(n==0) break;
47 memset(cost,0,sizeof(cost));
48 for(int i=0;i<n*(n-1)/2;i++){
49 int a,b,c;
50 scanf("%d%d%d",&a,&b,&c);
51 cost[a-1][b-1] = c;
52 cost[b-1][a-1] = c;
53 }
54 printf("%d\n",prim(0));
55 }
56 return 0;
57 }
Freecode : www.cnblogs.com/yym2013
hdu 1233:还是畅通工程(数据结构,图,最小生成树,普里姆(Prim)算法)
原文:http://www.cnblogs.com/yym2013/p/3556047.html