-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKruskal_MST.cpp
More file actions
139 lines (115 loc) · 2.78 KB
/
Kruskal_MST.cpp
File metadata and controls
139 lines (115 loc) · 2.78 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include<bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair < ll, ll > iPair;
map < iPair, ll > mp;
class Graph
{
ll V, E;
vector< pair < ll, iPair > > edges;
public:
Graph(ll V, ll E)
{
this->V = V;
this->E = E;
}
void addEdge(ll u, ll v, ll w)
{
edges.push_back({w, {u, v}});
}
// Function to find MST using Kruskal's MST algorithm
ll kruskalMST();
};
class DisjointSets // To represent Disjoint Sets
{
ll *parent, *rnk;
ll n;
public:
DisjointSets(ll n)
{
this->n = n;
parent = new ll[n+1];
rnk = new ll[n+1];
for (ll i = 0; i <= n; i++)
{
rnk[i] = 0;
parent[i] = i;
}
}
// Find the parent of a node 'u'
// Path Compression
ll findParent(ll u)
{
if (u != parent[u])
parent[u] = findParent(parent[u]);
return parent[u];
}
void merge(ll x, ll y) // Union by rank
{
x = findParent(x), y = findParent(y);
/* Make tree with smaller height
a subtree of the other tree */
if (rnk[x] > rnk[y])
parent[y] = x;
else // If rnk[x] <= rnk[y]
parent[x] = y;
if (rnk[x] == rnk[y])
rnk[y]++;
}
};
ll Graph::kruskalMST()
{
ll mst_wt = 0; // Initialize result
sort(edges.begin(), edges.end());
DisjointSets ds(V);
vector< pair < ll, iPair > > ::iterator it;
for (it = edges.begin(); it != edges.end(); it++)
{
ll u = it->second.first;
ll v = it->second.second;
ll set_u = ds.findParent(u);
ll set_v = ds.findParent(v);
// Check if the selected edge is creating a cycle or not (Cycle is created if u and v belong to same set)
if (set_u != set_v)
{
mst_wt += it->first;
ds.merge(set_u, set_v);
}
}
return mst_wt;
}
int main()
{
int t;
cin>>t;
for(int q = 1; q <= t; q++)
{
cout<<"Case #"<<q<<": ";
mp.clear();
ll V, E, black;
cin >> V >> black;
E = (V * (V-1)) / 2;
Graph g(V, E);
ll a, b;
for(ll i = 0; i < black; i++)
{
cin >> a >> b;
a--, b--;
if(a > b)
swap(a, b);
g.addEdge(a, b, 1);
mp[{a, b}] = 1;
}
for(ll i = 0; i < V-1; i++)
{
for(ll j = i+1; j < V; j++)
{
if(!mp.count({i, j}))
g.addEdge(i, j, 2);
}
}
ll mst_wt = g.kruskalMST();
cout << mst_wt << endl;
}
return 0;
}