帮我用c语言写一个代码,要求输入无向连通图顶点数与边数,并每行输入各边的顶点及其权值数据(顶点序号从0开始),采用Kruskal算法求解该无向连通图的最小生成树依久得到的边,并计算输出其权值。
时间: 2024-12-17 13:31:15 浏览: 12
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <malloc.h>
typedef struct Edge {
int src, dest, weight;
} Edge;
typedef struct Graph {
int vertices;
Edge** edges;
bool* visited;
} Graph;
int compare(const void* a, const void* b) {
return ((Edge*)a)->weight - ((Edge*)b)->weight;
}
void kruskal_mst(Graph* graph) {
int i, j, edge_count = 0;
qsort(graph- 1) / 2, sizeof(Edge), compare);
for (i = 0; i < graph->vertices && edge_count < graph->vertices - 1; i++) {
if (!graph->visited[i] && !graph->visited[(Edge*)graph->edges[edge_count].dest]) {
printf("Edge %d-%d with weight %d\n", graph->edges[edge_count].src, graph->edges[edge_count].dest, graph->edges[edge_count].weight);
graph->visited[i] = true;
graph->visited[(Edge*)graph->edges[edge_count].dest] = true;
edge_count++;
}
}
}
int main() {
int v, e, src, dest, weight;
printf("Enter number of vertices and edges: ");
scanf("%d %d", &v, &e);
Graph* g = (Graph*) malloc(sizeof(Graph));
g->vertices = v;
g->edges = (Edge**)malloc(v * (v - 1) * sizeof(Edge*));
g->visited = (bool*)malloc(v * sizeof(bool));
// Initialize visited array to false
for (int i = 0; i < v; i++)
g->visited[i] = false;
for (int i = 0; i < e; i++) {
printf("Enter edge (%d, %d) with weight: ", i, i + 1); // Assuming edges are undirected, input symmetrically
scanf("%d %d %d", &src, &dest, &weight);
Edge* edge = (Edge*)malloc(sizeof(Edge));
edge->src = src;
edge->dest = dest;
edge->weight = weight;
g->edges[i] = edge;
}
kruskal_mst(g);
free(g->edges);
free(g->visited);
free(g);
return 0;
}
阅读全文