#include <stdio.h>
#include <stdlib.h>
typedef struct Edge {
int u, v, weight;
} Edge;
typedef struct Graph {
int V, E;
Edge* edge;
} Graph;
// Function to compare edges based on their weights
int cmp(const void* a, const void* b) {
Edge* edgeA = (Edge*)a;
Edge* edgeB = (Edge*)b;
return edgeA->weight - edgeB->weight;
}
// Function to find the parent of a vertex in the DSU
int find(int parent[], int i) {
if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}
// Function to union two vertices in the DSU
void unionSet(int parent[], int x, int y) {
int xset = find(parent, x);
int yset = find(parent, y);
parent[xset] = yset;
}
// Function to implement Kruskal's Algorithm
void kruskal(Graph* graph) {
int V = graph->V;
Edge result[V];
int e = 0;
int i = 0;
// Sort all edges in non-decreasing order of their weights
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), cmp);
// Create a DSU data structure
int* parent = (int*)malloc(V * sizeof(int));
for (int v = 0; v < V; v++)
parent[v] = -1;
// Iterate through all edges
while (e < V - 1 && i < graph->E) {
Edge next_edge = graph->edge[i++];
int x = find(parent, next_edge.u);
int y = find(parent, next_edge.v);
// If the two vertices are not in the same connected component
if (x != y) {
result[e++] = next_edge;
unionSet(parent, x, y);
}
}
// Print the MST
printf("The edges of Minimum Cost Spanning Tree are:\n");
for (int j = 0; j < e; j++)
printf("Edge cost from %d to %d: %d\n", result[j].u, result[j].v, result[j].weight);
printf("Minimum cost of spanning tree = %d\n", result[e - 1].weight);
}
int main() {
int V, E;
printf("Enter the number of vertices: ");
scanf("%d", &V);
printf("Enter the number of edges: ");
scanf("%d", &E);
Graph* graph = createGraph(V, E);
printf("Enter the edges (source destination weight):\n");
for (int i = 0; i < E; i++) {
scanf("%d%d%d", &graph->edge[i].u, &graph->edge[i].v, &graph->edge[i].weight);
}
// Find and print the MST using Kruskal's Algorithm
kruskal(graph);
return 0;
}