-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkruskals_algorithm.cpp
107 lines (87 loc) · 2.24 KB
/
kruskals_algorithm.cpp
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
/*
Kruskal’s Algorithm builds the spanning tree by adding edges one by one into a growing spanning tree.
Kruskal's algorithm follows greedy approach as in each iteration it finds an edge which has least
weight and add it to the growing spanning tree.
Algorithm Steps:
Sort the graph edges with respect to their weights.
Start adding edges to the MST from the edge with the smallest weight until the edge of the largest weight.
Only add edges which doesn't form a cycle , edges which connect only disconnected components.
*/
#include <bits/stdc++.h>
using namespace std;
class Edge{
public:
int u, v, weight;
Edge(int src, int dest, int wt){
u = src;
v = dest;
weight = wt;
}
};
bool comp(Edge a, Edge b){
return (a.weight < b.weight);
}
//find operation for union-find algorithm of disjoint-sets data structure
int find(int i, int parent[]){
if(i == parent[i]){
return i;
}
return parent[i] = find(parent[i], parent);
}
//union operation for union-find algorithm of disjoint-sets data structure
void makeUnion(int u, int v, int parent[], int rank[]){
u = find(u, parent);
v = find(v, parent);
if(rank[u] < rank[v]){
parent[u] = v;
}
else if(rank[u] > rank[v]){
parent[v] = u;
}
else{
parent[v] = u;
rank[u]++;
}
}
int KruskalAlgorithm(int n, int m, vector<Edge> &edges){
//sort the edges based on their weights
sort(edges.begin(), edges.end(), comp);
//create disjoint set
int parent[n], rank[n];
for(int i = 0; i < n; i++){
parent[i] = i;
rank[i] = 0;
}
int mstCost = 0;
vector<Edge> mst;
//iterate over each edge from min. weight to max. weight
for(Edge e: edges){
//if the nodes at the end of this edge 'e' are already in
//same set then do not
//else add this edge to mst
int a = find(e.u, parent);
int b = find(e.v, parent);
if(a != b){
mstCost += e.weight;
mst.push_back(e);
makeUnion(a, b, parent, rank);
}
}
for(Edge e: mst){
cout << e.u << "-" << e.v << " weight: " << e.weight << endl;
}
return mstCost;
}
int main(){
int n, m;
cin >> n >> m;
vector<Edge> edges;
for(int i = 0; i < m; i++){
int f, s, wt;
cin >> f >> s >> wt;
edges.push_back(Edge(f,s,wt));
}
int mstCost = KruskalAlgorithm(n, m, edges);
cout << "cost of MST: " << mstCost << "\n";
return 0;
}