c实现克鲁斯卡尔最小生成树算法
时间: 2023-12-01 16:41:07 浏览: 76
以下是C语言实现克鲁斯卡尔最小生成树算法的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_EDGE_NUM 1000
#define MAX_VERTEX_NUM 100
typedef struct {
int u, v, w;
} Edge;
Edge edges[MAX_EDGE_NUM];
int parent[MAX_VERTEX_NUM];
int rank[MAX_VERTEX_NUM];
int cmp(const void *a, const void *b) {
return ((Edge *)a)->w - ((Edge *)b)->w;
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void merge(int x, int y) {
int px = find(x), py = find(y);
if (rank[px] > rank[py]) {
parent[py] = px;
} else {
parent[px] = py;
if (rank[px] == rank[py]) {
rank[py]++;
}
}
}
void kruskal(int n, int m) {
int i, cnt = 0;
for (i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
qsort(edges, m, sizeof(Edge), cmp);
for (i = 0; i < m; i++) {
int u = edges[i].u, v = edges[i].v, w = edges[i].w;
if (find(u) != find(v)) {
merge(u, v);
printf("%d %d %d\n", u, v, w);
cnt++;
if (cnt == n - 1) {
break;
}
}
}
}
int main() {
int n, m, i;
scanf("%d%d", &n, &m);
for (i = 0; i < m; i++) {
scanf("%d%d%d", &edges[i].u, &edges[i].v, &edges[i].w);
}
kruskal(n, m);
return 0;
}
```
阅读全文