c语言中根据kruskal算法,实现求最小生成树代码
时间: 2024-03-13 19:47:17 浏览: 71
Kruskal.zip_e-tree_kruskal_最小生成树_简述kruskal_;Kruskal算法
以下是C语言中使用Kruskal算法实现求最小生成树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
#define MAX_EDGES 10000
typedef struct {
int u, v;
int weight;
} Edge;
int parent[MAX_VERTICES];
int find(int i) {
if (parent[i] == i)
return i;
else
return find(parent[i]);
}
void union_set(int i, int j) {
int x = find(i);
int y = find(j);
parent[x] = y;
}
int cmp(const void* a, const void* b) {
return ((Edge*)a)->weight - ((Edge*)b)->weight;
}
void kruskal(Edge edges[], int n, int num_vertices) {
int i, num_edges = 0;
for (i = 0; i < num_vertices; i++)
parent[i] = i;
qsort(edges, n, sizeof(Edge), cmp);
for (i = 0; i < n && num_edges < num_vertices - 1; i++) {
int u = edges[i].u;
int v = edges[i].v;
if (find(u) != find(v)) {
union_set(u, v);
printf("(%d, %d) %d\n", u, v, edges[i].weight);
num_edges++;
}
}
}
int main() {
int num_vertices, num_edges, i;
Edge edges[MAX_EDGES];
scanf("%d%d", &num_vertices, &num_edges);
for (i = 0; i < num_edges; i++)
scanf("%d%d%d", &edges[i].u, &edges[i].v, &edges[i].weight);
kruskal(edges, num_edges, num_vertices);
return 0;
}
```
其中,`Edge`结构体用于表示一条边,`parent`数组用于记录每个节点的父节点,`find`和`union_set`函数用于并查集操作,`cmp`函数用于边的比较,`kruskal`函数用于实现Kruskal算法,`main`函数用于读入边的信息并调用`kruskal`函数求解最小生成树。
阅读全文