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