0% found this document useful (0 votes)
8 views2 pages

Krush

Uploaded by

23ucs649
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Krush

Uploaded by

23ucs649
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>

// Edge structure
typedef struct {
int u, v, weight;
} Edge;

// Union-Find structure
typedef struct {
int* parent;
int* rank;
} UnionFind;

// Function to create Union-Find structure


UnionFind* createUnionFind(int n) {
UnionFind* uf = (UnionFind*)malloc(sizeof(UnionFind));
uf->parent = (int*)malloc(n * sizeof(int));
uf->rank = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
uf->parent[i] = i;
uf->rank[i] = 0;
}
return uf;
}

// Find function with path compression


int find(UnionFind* uf, int u) {
if (uf->parent[u] != u) {
uf->parent[u] = find(uf, uf->parent[u]); // Path compression
}
return uf->parent[u];
}

// Union function with rank optimization


int unionSets(UnionFind* uf, int u, int v) {
int rootU = find(uf, u);
int rootV = find(uf, v);

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;
}

// Function to compare edges by weight for sorting


int compareEdges(const void* a, const void* b) {
Edge* edgeA = (Edge*)a;
Edge* edgeB = (Edge*)b;
return edgeA->weight - edgeB->weight;
}
// Kruskal's algorithm
void kruskalMST(Edge edges[], int n, int m) {
UnionFind* uf = createUnionFind(n);
qsort(edges, m, sizeof(Edge), compareEdges); // Sort edges by weight

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;
}
}

printf("Total weight of the Minimum Spanning Tree: %d\n", mstWeight);

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;
}

You might also like