c语言中根据kruskal算法,实现求最小生成树代码.并设计案例调用
时间: 2024-03-13 22:47:20 浏览: 58
最小生成树算法C语言代码实例
5星 · 资源好评率100%
以下是一个简单的案例,使用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;
int total_weight = 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);
total_weight += edges[i].weight;
num_edges++;
}
}
printf("Total weight: %d\n", total_weight);
}
int main() {
int num_vertices, num_edges, i;
Edge edges[MAX_EDGES];
printf("Enter the number of vertices and edges: ");
scanf("%d%d", &num_vertices, &num_edges);
printf("Enter the edges and their weights:\n");
for (i = 0; i < num_edges; i++)
scanf("%d%d%d", &edges[i].u, &edges[i].v, &edges[i].weight);
printf("The minimum spanning tree is:\n");
kruskal(edges, num_edges, num_vertices);
return 0;
}
```
在这个案例中,用户需要输入带权无向图的顶点数和边数,然后输入每条边的起点、终点和权重。程序会输出最小生成树的边及其权重总和。例如,对于下面的带权无向图:
```
2
0--------1
| |
| |
4| 3|
| |
| |
3--------4
5
```
用户可以输入以下内容:
```
Enter the number of vertices and edges: 5 7
Enter the edges and their weights:
0 1 2
0 3 4
0 4 3
1 4 3
1 2 3
2 4 5
3 4 5
```
程序会输出以下内容:
```
The minimum spanning tree is:
(0, 1) 2
(0, 4) 3
(1, 4) 3
(1, 2) 3
Total weight: 11
```
这表示最小生成树的边为(0,1)、(0,4)、(1,4)和(1,2),总权重为11。
阅读全文