Kruskal算法生成最小代价生成树c语言
时间: 2023-05-13 11:04:59 浏览: 103
Kruskal算法生成最小代价生成树的C语言实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_EDGE_NUM 100
#define MAX_VERTEX_NUM 100
typedef struct {
int u, v, w;
} Edge;
int cmp(const void* a, const void* b) {
return ((Edge*)a)->w - ((Edge*)b)->w;
}
int find(int* parent, int i) {
if (parent[i] == i) {
return i;
}
return parent[i] = find(parent, parent[i]);
}
void union_set(int* parent, int* rank, int x, int y) {
int px = find(parent, x);
int py = find(parent, y);
if (rank[px] < rank[py]) {
parent[px] = py;
} else if (rank[px] > rank[py]) {
parent[py] = px;
} else {
parent[px] = py;
rank[py]++;
}
}
void kruskal(Edge* edges, int n, int m) {
int parent[MAX_VERTEX_NUM], rank[MAX_VERTEX_NUM];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
qsort(edges, m, sizeof(Edge), cmp);
int cnt = 0;
for (int i = 0; i < m; i++) {
int u = edges[i].u;
int v = edges[i].v;
int w = edges[i].w;
if (find(parent, u) != find(parent, v)) {
printf("%d %d %d\n", u, v, w);
union_set(parent, rank, u, v);
cnt++;
if (cnt == n - 1) {
break;
}
}
}
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
Edge edges[MAX_EDGE_NUM];
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &edges[i].u, &edges[i].v, &edges[i].w);
}
kruskal(edges, n, m);
return 0;
}
```
注意:这段代码并不是最优解,仅供参考。
阅读全文