forked from ShivamDubey7/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy pathKruskals Algorithm - DSU
61 lines (58 loc) · 1.14 KB
/
Kruskals Algorithm - DSU
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
#include<bits/stdc++. h>
using namespace std;
const int N = 1e5+6;
vector<int> parent(N);
vector<int> sz(N);
void make_set(int v){
parent[v] = v;
sz[v] = 1;
}
int find_set(int v){
if(v == parent[v]){
return v;
}
return parent[v] = find_set(parent[v]);
}
void union_sets(int a, int b){
a = find_set(a);
b = find_set(b);
if(a != b){
if(sz[a] < sz[b]){
swap(a,b);
}
parent[b] = a;
sz[a] += sz[b];
}
}
int main(){
for(int i=0; i<N; i++){
make_set(i);
}
int n, m;
cin>>n>>m;
vector<vector<int> > edges;
for(int i=0; i<m; i++){
int u,v,w;
cin>>u>>v>>w;
edges.push_back({w,u,v});
}
sort(edges.begin(), edges.end());
int cost = 0;
for(auto i : edges){
int u = i[1];
int v = i[2];
int w = i[0];
int x = find_set(u);
int y = find_set(v);
if(x == y){
//makes a cycle
continue;
}
else{
cost += w;
union_sets(u, v);
}
}
cout<<cost<<"\n";
return 0;
}