ASSIGNMENT-15
Q. Find the minimal spanning tree by implementing Kruskal's
algorithm.
#include <stdio.h>
#define MAX 30
typedef struct {
int u, v, w;
} Edge;
int parent[MAX];
int find(int x) {
while (parent[x] != x)
x = parent[x];
return x;
}
void unionSet(int a, int b) {
int rootA = find(a);
int rootB = find(b);
parent[rootB] = rootA;
}
int main() {
int n, e;
Edge edges[MAX], mst[MAX];
printf("Enter number of vertices: ");
scanf("%d", &n);
printf("Enter number of edges: ");
scanf("%d", &e);
printf("Enter edges (u v weight):\n");
for (int i = 0; i < e; i++) {
scanf("%d %d %d", &edges[i].u, &edges[i].v, &edges[i].w);
}
for (int i = 0; i < n; i++)
parent[i] = i;
for (int i = 0; i < e - 1; i++) {
for (int j = 0; j < e - i - 1; j++) {
if (edges[j].w > edges[j + 1].w) {
Edge temp = edges[j];
edges[j] = edges[j + 1];
edges[j + 1] = temp;
}
}
}
int count = 0, totalCost = 0;
for (int i = 0; i < e; i++) {
int u = edges[i].u;
int v = edges[i].v;
if (find(u) != find(v)) {
mst[count++] = edges[i];
totalCost += edges[i].w;
unionSet(u, v);
}
}
printf("\nMinimum Spanning Tree (Kruskal's Algorithm):\n");
for (int i = 0; i < count; i++) {
printf("%d -- %d (weight = %d)\n", mst[i].u, mst[i].v, mst[i].w);
}
printf("\nTotal Minimum Cost = %d\n", totalCost);
return 0;
}
OUTPUT :