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

输入:顶点个数n和边数m,然后输入m行,每行输入格式:u v w 分别表示两个顶点和这个边的权值,顶点序号从1开始

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

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <algorithm>
 4 using namespace std;
 5 #define MAXN 1000
 6 #define MAXM 1000
 7 int parent[MAXN], n, m;
 8 typedef struct Edge {
 9     int u, v, w;
10     bool operator < (const Edge &other) const {
11         return w < other.w;
12     }
13 }Edge;
14 Edge edge[MAXM];
15 void init() {
16     for (int i = 1; i <= n; ++i) parent[i] = -1;
17 }
18 int Find(int x) {
19     int s = x, tmp;
20     while (parent[s] >= 0) s = parent[s];
21     while (s != x) {
22         tmp = parent[x]; parent[x] = s; x = tmp;
23     }
24     return s;
25 }
26 void Union(int a, int b) {
27     int x = Find(a), y = Find(b), tmp = parent[x] + parent[y];
28     if (parent[x] < parent[y]) {
29         parent[y] = x; parent[x] = tmp;
30     } else {
31         parent[x] = y; parent[y] = tmp;
32     }
33 }
34 void kruscal() {
35     int cnt = 0, sum = 0, i, u, v, w;
36     for (i = 0; i < m; ++i) {
37         u = edge[i].u; v = edge[i].v; w = edge[i].w;
38         if (Find(u) != Find(v)) {
39             cnt++; sum += w; printf("%d %d %d\n", u, v, w); Union(u, v);
40         }
41         if (cnt == n - 1) break;
42     }
43     printf("%d\n", sum);
44 }
45 int main(void) {
46     freopen("kruscal.in", "r", stdin);
47     while (~scanf("%d%d", &n, &m)) {
48         int i, u, v, w;
49         for (i = 0; i < m; ++i) {
50             scanf("%d%d%d", &u, &v, &w); edge[i].u = u; edge[i].v = v; edge[i].w = w;
51         }
52         init(); sort(edge, edge+m); kruscal();
53     }
54 
55     return 0;
56 }

呵呵

posted on 2013-05-01 12:08  aries__liu  阅读(260)  评论(0编辑  收藏  举报