1
+ /* *
2
+ * Kruskal's algorithm to find MSTof a given connected, undirected and
3
+ * weighted graph.
4
+ */
5
+ #include < bits/stdc++.h>
6
+ using namespace std ;
7
+
8
+ // DisjointSet class to implements Find and Union operations.
9
+ class DisjointSet {
10
+ unordered_map<int , int > parent;
11
+ unordered_map<int , int > rank;
12
+ public:
13
+ DisjointSet (int n) {
14
+ for (int i = 0 ; i < n; i++) {
15
+ parent.insert (pair<int , int >(i, i));
16
+ rank.insert (pair<int , int >(i, 0 ));
17
+ }
18
+ }
19
+ int Find (int x) {
20
+ if (parent[x] == x)
21
+ return x;
22
+ else
23
+ return Find (parent[x]);
24
+ }
25
+ void Union (int x, int y) {
26
+ if (rank[x] > rank[y])
27
+ parent[y] = x;
28
+ else if (rank[y] > rank[x])
29
+ parent[x] = y;
30
+ else if (rank[x] == rank[y]) {
31
+ parent[x] = y;
32
+ rank[y]++;
33
+ }
34
+ }
35
+ };
36
+
37
+ class Graph {
38
+ int v, e;
39
+ vector<pair<int ,pair<int ,int >>> edges;
40
+ public:
41
+ Graph (int nv, int ne) : v(nv), e(ne) {}
42
+ void add_edge (int u, int v, int wt) {
43
+ edges.push_back (make_pair (wt, make_pair (u, v)));
44
+ }
45
+ void kruskal ();
46
+ };
47
+
48
+ void Graph::kruskal () {
49
+ DisjointSet dset (v);
50
+
51
+ sort (edges.begin (), edges.end ());
52
+
53
+ vector<pair<int , pair<int , int >>> mst;
54
+ int mst_wt = 0 ;
55
+
56
+ for (auto it = edges.begin (); it != edges.end (); ++it) {
57
+ int u = it->second .first , v = it->second .second ;
58
+ int u_set = dset.Find (u), v_set = dset.Find (v);
59
+
60
+ if (u_set != v_set) {
61
+ mst.push_back (make_pair (it->first , make_pair (u, v)));
62
+ dset.Union (u_set, v_set);
63
+ mst_wt += it->first ;
64
+ }
65
+ }
66
+ cout << mst_wt << endl;
67
+ }
68
+
69
+ int main () {
70
+ Graph g (6 , 8 );
71
+
72
+ g.add_edge (0 , 1 , 4 );
73
+ g.add_edge (0 , 5 , 2 );
74
+ g.add_edge (1 , 2 , 6 );
75
+ g.add_edge (1 , 5 , 5 );
76
+ g.add_edge (2 , 3 , 3 );
77
+ g.add_edge (2 , 5 , 1 );
78
+ g.add_edge (3 , 4 , 2 );
79
+ g.add_edge (4 , 5 , 4 );
80
+
81
+ g.kruskal ();
82
+
83
+ return 0 ;
84
+ }
85
+ // Time Complexity: O(E * LogE) for sorting edges + O(LogV) time for
86
+ // find-union algorithm So, overall complexity is O(E * LogE + LogV).
0 commit comments