#include <stdio.h>
#include <stdlib.h>
#define MAX_EDGES 100
#define MAX_VERTICES 100
// Edge structure
typedef struct {
int src, dest, weight;
} Edge;
// Disjoint Set Union (Union-Find) structure
int parent[MAX_VERTICES];
// Find root parent with path compression
int find(int i) {
if (parent[i] != i)
parent[i] = find(parent[i]); // compress path
return parent[i];
}
// Union two sets
void union_sets(int a, int b) {
int rootA = find(a);
int rootB = find(b);
if (rootA != rootB) {
parent[rootB] = rootA; // attach rootB to rootA
}
}
// Compare function for qsort to sort edges by weight
int compare(const void* a, const void* b) {
Edge* e1 = (Edge*)a;
Edge* e2 = (Edge*)b;
return e1->weight - e2->weight;
}
// Kruskal's algorithm
void kruskal(Edge edges[], int E, int V) {
// Initialize disjoint sets
for (int i = 0; i < V; i++) {
parent[i] = i;
}
// Sort edges by weight
qsort(edges, E, sizeof(Edge), compare);
printf("Edges in MST:\n");
int mst_weight = 0;
int count = 0;
for (int i = 0; i < E && count < V - 1; i++) {
int u = edges[i].src;
int v = edges[i].dest;
// Check if adding this edge creates a cycle
if (find(u) != find(v)) {
union_sets(u, v); // union sets
printf("%c - %c : %d\n", 'A' + u, 'A' + v, edges[i].weight);
mst_weight += edges[i].weight;
count++;
}
}
printf("Total MST weight: %d\n", mst_weight);
}
int main() {
// Vertices: A=0, B=1, C=2, D=3
int V = 4;
int E = 4;
Edge edges[] = {
{0, 2, 1}, // A-C
{0, 1, 2}, // A-B
{1, 2, 3}, // B-C
{2, 3, 4} // C-D
};
kruskal(edges, E, V);
return 0;
}
for (int i = 0; i < V; i++) { parent[i] = i; }
Initialize each vertex as its own set
qsort(edges, E, sizeof(Edge), compare);
Sort edges by weight ascending
if (find(u) != find(v)) {
Check if edge connects two different sets to avoid cycles
Merge sets after adding edge to MST
printf("%c - %c : %d\n", 'A' + u, 'A' + v, edges[i].weight);
Print edge added to MST
Edges in MST:
A - C : 1
A - B : 2
C - D : 4
Total MST weight: 7