利用c++编写一段代码,使用kruscal算法求得图的最小生成树
时间: 2023-06-13 13:03:08 浏览: 99
图的最小生成树的C++代码
以下是使用Kruskal算法求图的最小生成树的C代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
#define MAX_EDGE_NUM 100
typedef struct {
int begin, end; // 边的起点和终点
int weight; // 边的权值
} Edge;
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 存储图中的所有顶点
Edge edge[MAX_EDGE_NUM]; // 存储图中所有的边
int v_num, e_num; // 顶点数和边数
} Graph;
void init(Graph *G) {
int i;
for (i = 0; i < MAX_VERTEX_NUM; i++) {
G->vertex[i] = -1; // 初始化顶点数组
}
G->v_num = 0;
G->e_num = 0;
}
int find(int *parent, int f) {
while (parent[f] > 0) {
f = parent[f];
}
return f;
}
void kruskal(Graph G) {
int i, j, k;
int parent[MAX_VERTEX_NUM];
for (i = 0; i < G.v_num; i++) {
parent[i] = 0;
}
for (i = 0; i < G.e_num - 1; i++) {
for (j = i + 1; j < G.e_num; j++) {
if (G.edge[i].weight > G.edge[j].weight) { // 按权值从小到大排序
Edge temp = G.edge[i];
G.edge[i] = G.edge[j];
G.edge[j] = temp;
}
}
}
printf("最小生成树的边为:\n");
for (i = 0; i < G.e_num; i++) {
int begin = G.edge[i].begin;
int end = G.edge[i].end;
int w = G.edge[i].weight;
int pb = find(parent, begin);
int pe = find(parent, end);
if (pb != pe) {
parent[pb] = pe;
printf("(%d, %d) %d\n", begin, end, w);
}
}
}
int main() {
Graph G;
int i, j, k;
printf("请输入顶点数和边数:\n");
scanf("%d%d", &G.v_num, &G.e_num);
printf("请输入顶点信息:\n");
for (i = 0; i < G.v_num; i++) {
scanf("%d", &G.vertex[i]);
}
printf("请输入边的信息:\n");
for (i = 0; i < G.e_num; i++) {
scanf("%d%d%d", &G.edge[i].begin, &G.edge[i].end, &G.edge[i].weight);
}
kruskal(G);
return 0;
}
```
其中,函数`init()`用于初始化图的顶点数组和边数,函数`find()`用于查找顶点的根节点,函数`kruskal()`用于实现Kruskal算法,函数`main()`用于输入图的顶点和边的信息,并调用`kruskal()`函数求解最小生成树。
阅读全文