最小生成树示例程序_Prim算法

输入:顶点个数n和边数m,然后是m条边的数据。u v w 分别代表两个顶点和权值。顶点从1开始记起。

输出:一次选择的各条边和最小生成树的权。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <cctype>
 6 #include <stack>
 7 #include <queue>
 8 #include <map>
 9 #include <set>
10 #include <vector>
11 #include <cmath>
12 #include <algorithm>
13 #define lson l, m, rt<<1
14 #define rson m+1, r, rt<<1|1
15 using namespace std;
16 typedef long long int LL;
17 const int MAXN =  0x3f3f3f3f;
18 const int  MIN =  -0x3f3f3f3f;
19 const double eps = 1e-9;
20 const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
21   {1,1},{1,-1},{-1,-1}};
22 const int MAX = 100;
23 int n, m, lowcost[MAX], nearvex[MAX], edge[MAX][MAX];
24 void prim(int u0)
25 {
26   int i, j, sum = 0;
27   for (i = 1; i <= n; ++i) {
28     lowcost[i] = edge[u0][i]; nearvex[i] = u0;
29   }
30   nearvex[u0] = -1;
31   for (i = 1; i < n; ++i) {
32     int min = MAXN, v = -1;
33     for (j = 1; j <= n; ++j) {
34       if (nearvex[j] != -1 && lowcost[j] < min) {
35         min = lowcost[j]; v = j;
36       }
37     }
38     if (v != -1) {
39       printf("%d %d %d\n", nearvex[v], v, lowcost[v]);
40       sum += lowcost[v];
41       nearvex[v] = -1;
42       for (j = 1; j <= n; ++j) {
43         if (nearvex[j] != -1 && lowcost[j] > edge[v][j]) {
44           lowcost[j] = edge[v][j]; nearvex[j] = v;
45         }
46       }
47     }
48   }
49   printf("MST sum is : %d\n", sum);
50 }
51 
52 int main(void){
53 #ifndef ONLINE_JUDGE
54   freopen("prim.in", "r", stdin);
55 #endif
56   while (~scanf("%d%d", &n, &m)) {
57     int i, j, u, v, w;
58     memset(edge, 0, sizeof(edge));
59     for (i = 1; i <= m; ++i) {
60         scanf("%d%d%d", &u, &v, &w);
61         edge[u][v] = edge[v][u] = w;
62     }
63     for (i = 1; i <= n; ++i) {
64       for (j = 1; j <= n; ++j) {
65         if (i == j) edge[i][j] = 0;
66         else if (edge[i][j] == 0) edge[i][j] = MAXN;
67       }
68     }
69     prim(1);
70   }
71 
72   return 0;
73 }

写代码的时候,还是会出现各种错误,比如for循环里面到底是不是要取到等号,一定要想清楚,还有就是细节,输入的m和n不要搞错了。

posted on 2013-05-03 01:04  aries__liu  阅读(295)  评论(0编辑  收藏  举报