-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKrusKal.cpp
More file actions
80 lines (71 loc) · 1.92 KB
/
KrusKal.cpp
File metadata and controls
80 lines (71 loc) · 1.92 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
class DSU {
vector<int> rank, parent, size;
public:
DSU(int n) {
rank.resize(n + 1, 0);
parent.resize(n + 1);
size.resize(n + 1);
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
int findUPar(int node) {
if (node == parent[node])
return node;
return parent[node] = findUPar(parent[node]);
}
void unionByRank(int u, int v) {
int ulp_u = findUPar(u);
int ulp_v = findUPar(v);
if (ulp_u == ulp_v) return;
if (rank[ulp_u] < rank[ulp_v]) {
parent[ulp_u] = ulp_v;
}
else if (rank[ulp_v] < rank[ulp_u]) {
parent[ulp_v] = ulp_u;
}
else {
parent[ulp_v] = ulp_u;
rank[ulp_u]++;
}
}
void unionBySize(int u, int v) {
int ulp_u = findUPar(u);
int ulp_v = findUPar(v);
if (ulp_u == ulp_v) return;
if (size[ulp_u] < size[ulp_v]) {
parent[ulp_u] = ulp_v;
size[ulp_v] += size[ulp_u];
}
else {
parent[ulp_v] = ulp_u;
size[ulp_u] += size[ulp_v];
}
}
};
class Kruskal
{
public:
//Function to find sum of weights of edges of the Minimum Spanning Tree.
int spanningTree(int V, vector<vector<int>> adj[])
{
vector<pair<int,pair<int,int>>>edges ;
for(int i=0 ; i<V ; ++i){
for(auto &it : adj[i]){
edges.push_back({it[1] , {i , it[0]}});
}
}
DSU dsu(V) ;
sort(edges.begin(),edges.end());
int mstWt = 0 ;
for(auto &it : edges){
int u = it.second.first , v = it.second.second , wt = it.first ;
if(dsu.findUPar(u)!=dsu.findUPar(v)){
mstWt += wt ;
dsu.unionBySize(u,v);
}
}
return mstWt ;
}
};