-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkuruskals_logn.cpp
59 lines (51 loc) · 1.21 KB
/
kuruskals_logn.cpp
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
#include<bits/stdc++.h>
using namespace std;
struct node {
int parent, setsize;
};
struct edge {
int src, dest, wt;
};
edge edges[100];
node nodes[100];
vector<edge> final;
bool cmp(const edge& e1, const edge& e2) {
return (e1.wt < e2.wt);
}
int findroot(int i) {
if(nodes[i].parent != i)
nodes[i].parent = findroot(nodes[i].parent);
return nodes[i].parent;
}
int takeunion(int x, int y) {
int xroot = findroot(x);
int yroot = findroot(y);
if(nodes[yroot].setsize >= nodes[xroot].setsize)
nodes[xroot].parent = yroot;
else
nodes[xroot].parent = yroot;
nodes[xroot].setsize = nodes[yroot].setsize = nodes[xroot].setsize + nodes[yroot].setsize;
}
int main() {
int n, e;
cin>>n>>e;
for(int i = 0; i < n; i++) {
nodes[i].parent = i;
nodes[i].setsize = 1;
}
for(int i = 0; i < e; i++) {
cin>>edges[i].src>>edges[i].dest>>edges[i].wt;
}
sort(edges, edges + e, cmp);
for(int i = 0; i < e; i++) {
if(findroot(edges[i].src) != findroot(edges[i].dest)) {
final.push_back(edges[i]);
takeunion(edges[i].src, edges[i].dest);
}
}
cout<<endl;
for(int i = 0; i < final.size(); i++) {
cout<<final[i].src<<" "<<final[i].dest<<endl;
}
return 0;
}