-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathKruskals_algorithm_by_DSU.cpp
More file actions
62 lines (61 loc) · 1.13 KB
/
Kruskals_algorithm_by_DSU.cpp
File metadata and controls
62 lines (61 loc) · 1.13 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
#include<bits/stdc++.h>
using namespace std;
#define int long long int
#define f(i,a,n) for(int i=a;i<n;i++)
#define vi vector<int>
#define vvi vector<vector<int>>
#define pb push_back
#define se(a) a.begin(),a.end()
const int N = 1e5+6;
vi parent(N);
vi sz(N);
void make_set(int j)
{
parent[j] = j;
sz[j] = 1;
}
int find_set(int j) {
if(j==parent[j]) return j;
return parent[j] = find_set(parent[j]);
}
void union_set(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];
}
}
int32_t main()
{
f(i,0,N){
make_set(i);
}
int n,m;
cin>>n>>m;
vvi edges;
f(i,0,m){
int w,u,v;
cin>>u>>v>>w;
edges.pb({w,u,v});
}
sort(se(edges));
int cost=0;
for(auto it : edges){
int w=it[0],u=it[1],v=it[2];
int p1=find_set(u),p2=find_set(v);
if(p1==p2){
continue;
}
else{
cout<<u<<" "<<v<<endl;
cost+=w;
union_set(p1,p2);
}
}
cout<<cost<<endl;
return 0;
}