Skip to content

Commit 98385fd

Browse files
Merge pull request #218 from harshendram/Algo/Kruskal
Added the Kruskal algo implementation in c
2 parents 5ca0ecd + dfc2c17 commit 98385fd

1 file changed

Lines changed: 81 additions & 0 deletions

File tree

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
#include <numeric>
5+
6+
struct Edge
7+
{
8+
int src, dest, weight;
9+
};
10+
11+
struct DSU
12+
{
13+
std::vector<int> parent;
14+
DSU(int n)
15+
{
16+
parent.resize(n);
17+
std::iota(parent.begin(), parent.end(), 0);
18+
}
19+
20+
int find(int i)
21+
{
22+
if (parent[i] == i)
23+
return i;
24+
return parent[i] = find(parent[i]);
25+
}
26+
27+
void unite(int i, int j)
28+
{
29+
int root_i = find(i);
30+
int root_j = find(j);
31+
if (root_i != root_j)
32+
{
33+
parent[root_i] = root_j;
34+
}
35+
}
36+
};
37+
38+
bool compareEdges(const Edge &a, const Edge &b)
39+
{
40+
return a.weight < b.weight;
41+
}
42+
43+
void kruskalMST(int V, std::vector<Edge> &edges)
44+
{
45+
std::vector<Edge> result;
46+
std::sort(edges.begin(), edges.end(), compareEdges);
47+
48+
DSU dsu(V);
49+
int total_weight = 0;
50+
51+
for (const auto &edge : edges)
52+
{
53+
int src_root = dsu.find(edge.src);
54+
int dest_root = dsu.find(edge.dest);
55+
56+
if (src_root != dest_root)
57+
{
58+
result.push_back(edge);
59+
dsu.unite(src_root, dest_root);
60+
total_weight += edge.weight;
61+
}
62+
}
63+
64+
std::cout << "Edges in the Minimum Spanning Tree:" << std::endl;
65+
for (const auto &edge : result)
66+
{
67+
std::cout << edge.src << " -- " << edge.dest << " == " << edge.weight << std::endl;
68+
}
69+
std::cout << "Total weight of MST: " << total_weight << std::endl;
70+
}
71+
72+
int main()
73+
{
74+
int V = 4;
75+
std::vector<Edge> edges = {
76+
{0, 1, 10}, {0, 2, 6}, {0, 3, 5}, {1, 3, 15}, {2, 3, 4}};
77+
78+
kruskalMST(V, edges);
79+
80+
return 0;
81+
}

0 commit comments

Comments
 (0)