-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathkruskalsAlgorithm.cpp
More file actions
119 lines (100 loc) · 2.43 KB
/
kruskalsAlgorithm.cpp
File metadata and controls
119 lines (100 loc) · 2.43 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
// Data structure to store graph edges
struct Edge {
int src, dest, weight;
};
// Class to represent a disjoint set
class DisjointSet
{
unordered_map<int, int> parent;
public:
// perform MakeSet operation
void makeSet(int N)
{
// create N disjoint sets (one for each vertex)
for (int i = 0; i < N; i++)
parent[i] = i;
}
// Find the root of the set in which element k belongs
int Find(int k)
{
// if k is root
if (parent[k] == k)
return k;
// recur for parent until we find root
return Find(parent[k]);
}
// Perform Union of two subsets
void Union(int a, int b)
{
// find root of the sets in which elements
// x and y belongs
int x = Find(a);
int y = Find(b);
parent[x] = y;
}
};
// construct MST using Kruskal's algorithm
vector<Edge> KruskalAlgo(vector<Edge> edges, int N)
{
// stores edges present in MST
vector<Edge> MST;
// initialize DisjointSet class
DisjointSet ds;
// create singleton set for each element of universe
ds.makeSet(N);
// MST contains exactly V-1 edges
while (MST.size() != N - 1)
{
// consider next edge with minimum weight from the graph
Edge next_edge = edges.back();
edges.pop_back();
// find root of the sets to which two endpoint
// vertices of next_edge belongs
int x = ds.Find(next_edge.src);
int y = ds.Find(next_edge.dest);
// if both endpoints have different parents, they belong to
// different connected components and can be included in MST
if (x != y)
{
MST.push_back(next_edge);
ds.Union(x, y);
}
}
return MST;
}
// Comparison object to be used to order the Edges
struct compare
{
inline bool operator() (Edge const &a, Edge const &b)
{
return (a.weight > b.weight);
}
};
// main function
int main()
{
// vector of graph edges as per above diagram.
vector<Edge> edges =
{
// (u, v, w) tiplet represent undirected edge from
// vertex u to vertex v having weight w
{ 0, 1, 7 }, { 1, 2, 8 }, { 0, 3, 5 }, { 1, 3, 9 },
{ 1, 4, 7 }, { 2, 4, 5 }, { 3, 4, 15 }, { 3, 5, 6 },
{ 4, 5, 8 }, { 4, 6, 9 }, { 5, 6, 11 }
};
// sort edges by increasing weight
sort(edges.begin(), edges.end(), compare());
// Number of vertices in the graph
int N = 7;
// construct graph
vector<Edge> e = KruskalAlgo(edges, N);
for (Edge &edge: e)
cout << "(" << edge.src << ", " << edge.dest << ", "
<< edge.weight << ")" << endl;
return 0;
}