[算法] kruskal最小生成树算法

#include <stdio.h>
#include <stdlib.h>

#define MAX 100

int N, M;

struct Edge {
int u,v;
int weight;
} edge[MAX];

int vertexs[MAX];
int parents[MAX];

int edge_cmp(const void* a, const void* b) {
return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight;
}

int parents_find(int x) {
int s;
for(s = x; parents[s] >= 0; s = parents[s]){
;
}
return s;
}

void parents_union(int r1, int r2) {
int s1, s2;
int tmp;
s1 = parents_find(r1);
s2 = parents_find(r2);
tmp = parents[s1] + parents[s2];
if(parents[s1] < parents[s2]) {
parents[s2] = s1;
parents[s1] = tmp;
}
else {
parents[s1] = s2;
parents[s2] = tmp;
}
}

void kruskal() {
int sum_weight = 0;
int num = 0;
int i, u, v;
for(i = 0; i < M; i++) {
u = edge[i].u;
v = edge[i].v;
if(parents_find(u) != parents_find(v)) {
printf("%d %d %d\n", u + 1, v + 1, edge[i].weight);
num ++;
sum_weight += edge[i].weight;
parents_union(parents_find(u), parents_find(v));
}
if(num == N -1) {
break;
}
}
printf("weight of MST is %d\n", sum_weight);
}

int main() {
int i;
int u, v, w;

while(1) {
scanf("%d%d", &N, &M);
if(N == 0 && M == 0) {
break;
}
/* init */
for(i = 0; i < N; i++) {
vertexs[i] = i;
parents[i] = -1;
}

for(i = 0; i < M; i++) {
scanf("%d%d%d", &u, &v, &w);
u --;
v --;
edge[i].u = u;
edge[i].v = v;
edge[i].weight = w;
}

/* sort */
qsort(edge, M, sizeof(edge[0]), edge_cmp);
kruskal();
}

return 0;
}


posted @ 2014-01-08 16:44 ~嘉言懿行~~我是煲仔饭~~ 阅读(...) 评论(...) 编辑 收藏