最小生成树kruskal算法C++的代码
时间: 2023-11-12 07:09:21 浏览: 196
好的,以下是最小生成树kruskal算法C代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
#define MAX_EDGES MAX_VERTICES * (MAX_VERTICES - 1) / 2
typedef struct {
int start, end, weight;
} Edge;
typedef struct {
int parent, rank;
} Subset;
int V, E;
Edge edges[MAX_EDGES];
void input() {
scanf("%d %d", &V, &E);
for (int i = 0; i < E; i++) {
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
edges[i] = (Edge){ u, v, w };
}
}
int cmp(const void* a, const void* b) {
return (((Edge*)a)->weight < ((Edge*)b)->weight) ? -1 : 1;
}
int find(Subset* subsets, int i) {
if (subsets[i].parent != i) {
subsets[i].parent = find(subsets, subsets[i].parent);
}
return subsets[i].parent;
}
void unionSubsets(Subset* subsets, int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank) {
subsets[xroot].parent = yroot;
} else if (subsets[xroot].rank > subsets[yroot].rank) {
subsets[yroot].parent = xroot;
} else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
void kruskal(Edge* result) {
int idx = 0;
Subset subsets[MAX_VERTICES];
qsort(edges, E, sizeof(Edge), cmp);
for (int i = 0; i < V; i++) {
subsets[i] = (Subset) { i, 0 };
}
for (int i = 0; i < E; i++) {
int u = edges[i].start;
int v = edges[i].end;
int set_u = find(subsets, u);
int set_v = find(subsets, v);
if (set_u != set_v) {
result[idx++] = edges[i];
unionSubsets(subsets, set_u, set_v);
}
}
}
void output(Edge* result) {
printf("Minimum Spanning Tree Using Kruskal's Algorithm:\n");
int sum = 0;
for (int i = 0; i < V - 1; i++) {
printf("(%d, %d) %d\n", result[i].start, result[i].end, result[i].weight);
sum += result[i].weight;
}
printf("Total weight: %d\n", sum);
}
int main() {
input();
Edge result[MAX_VERTICES];
kruskal(result);
output(result);
return 0;
}
```
请问还有什么我可以帮到您的吗?
阅读全文