帮我用c语言写一个用克鲁斯卡尔算法写的最小生成树
时间: 2024-03-10 08:51:17 浏览: 64
好的,下面是用C语言实现的Kruskal算法求最小生成树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20 // 最大顶点数
#define MAX_EDGE_NUM 50 // 最大边数
typedef struct {
int u, v; // 边的两个顶点
int weight; // 边权值
} Edge;
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 存储顶点
Edge edge[MAX_EDGE_NUM]; // 存储边
int edgeNum; // 边的数量
int vertexNum; // 顶点的数量
} Graph;
void initGraph(Graph* graph, int vertexNum) {
graph->edgeNum = 0;
graph->vertexNum = vertexNum;
for (int i = 0; i < vertexNum; i++) {
graph->vertex[i] = i;
}
}
int find(int parent[], int i) {
while (parent[i] != i) {
i = parent[i];
}
return i;
}
void unionSet(int parent[], int x, int y) {
int xRoot = find(parent, x);
int yRoot = find(parent, y);
parent[xRoot] = yRoot;
}
int cmp(const void* a, const void* b) {
return ((Edge*)a)->weight - ((Edge*)b)->weight;
}
void kruskal(Graph* graph) {
int parent[MAX_VERTEX_NUM];
for (int i = 0; i < graph->vertexNum; i++) {
parent[i] = i;
}
qsort(graph->edge, graph->edgeNum, sizeof(Edge), cmp);
for (int i = 0; i < graph->edgeNum; i++) {
int u = graph->edge[i].u;
int v = graph->edge[i].v;
int weight = graph->edge[i].weight;
int uRoot = find(parent, u);
int vRoot = find(parent, v);
if (uRoot != vRoot) {
printf("Edge %d:(%d, %d) weight: %d\n", i, u, v, weight);
unionSet(parent, u, v);
}
}
}
int main() {
Graph graph;
int vertexNum = 6;
initGraph(&graph, vertexNum);
graph.edgeNum = 9;
graph.edge[0].u = 0;
graph.edge[0].v = 1;
graph.edge[0].weight = 1;
graph.edge[1].u = 0;
graph.edge[1].v = 2;
graph.edge[1].weight = 6;
graph.edge[2].u = 0;
graph.edge[2].v = 3;
graph.edge[2].weight = 5;
graph.edge[3].u = 1;
graph.edge[3].v = 2;
graph.edge[3].weight = 3;
graph.edge[4].u = 1;
graph.edge[4].v = 4;
graph.edge[4].weight = 2;
graph.edge[5].u = 2;
graph.edge[5].v = 3;
graph.edge[5].weight = 4;
graph.edge[6].u = 2;
graph.edge[6].v = 4;
graph.edge[6].weight = 7;
graph.edge[7].u = 3;
graph.edge[7].v = 5;
graph.edge[7].weight = 9;
graph.edge[8].u = 4;
graph.edge[8].v = 5;
graph.edge[8].weight = 8;
kruskal(&graph);
return 0;
}
```
这份代码使用了并查集来判断两个顶点是否在同一个连通分量中,从而避免了生成环。时间复杂度为O(ElogE),其中E为边的数量。
阅读全文