Krush
Krush
h>
#include <stdlib.h>
// Edge structure
typedef struct {
int u, v, weight;
} Edge;
// Union-Find structure
typedef struct {
int* parent;
int* rank;
} UnionFind;
if (rootU != rootV) {
if (uf->rank[rootU] > uf->rank[rootV]) {
uf->parent[rootV] = rootU;
} else if (uf->rank[rootU] < uf->rank[rootV]) {
uf->parent[rootU] = rootV;
} else {
uf->parent[rootV] = rootU;
uf->rank[rootU]++;
}
return 1;
}
return 0;
}
int mstWeight = 0;
printf("Edges in the Minimum Spanning Tree:\n");
for (int i = 0; i < m; i++) {
if (unionSets(uf, edges[i].u, edges[i].v)) {
printf("%d -- %d == %d\n", edges[i].u, edges[i].v, edges[i].weight);
mstWeight += edges[i].weight;
}
}
free(uf->parent);
free(uf->rank);
free(uf);
}
int main() {
// Example graph with 4 vertices and 5 edges
Edge edges[] = {{0, 1, 10}, {0, 2, 6}, {0, 3, 5}, {1, 3, 15}, {2, 3, 4}};
int n = 4; // Number of vertices
int m = 5; // Number of edges
kruskalMST(edges, n, m);
return 0;
}