-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathKruskal.cpp
96 lines (92 loc) · 2.46 KB
/
Kruskal.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
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
#include<bits/std++.h>
using namespace std;
struct edge{int src,des,weight;};
class UnionFind {
int *parent, *ranks, _size;
public:
UnionFind(){
}
UnionFind(int size){
parent = new int[size]; ranks = new int[size];
for(int element = 0 ; element < size ; element++){
parent[element] = element , ranks[element] = 0 ;
}
_size = size;
}
void resize(int size){
parent = new int[size]; ranks = new int[size];
for(int element = 0 ; element < size ; element++){
parent[element] = element , ranks[element] = 0 ;
}
_size = size;
}
int find(int element){
if(parent[element] == element){
return element;
}
else{
return parent[element] = find(parent[element]); // Path Compression algorithm
}
}
bool connected(int x,int y){
if(find(x) == find(y)){
return true;
}
else{
return false;
}
}
void merge(int x,int y){
x = find(x);
y = find(y);
if(x != y){ // Union by Rank algorithm
if(ranks[x] > ranks[y]){
parent[y] = x;
}
else if(ranks[x] < ranks[y]){
parent[x] = y;
}
else{
parent[x] = y; ranks[y] ++ ;
}
_size--;
}
}
void clear(){
delete [] parent; delete [] ranks;
}
int size(){
return _size;
}
};
bool comparator(const edge &a,const edge &b){
return a.weight < b.weight;
}
vector<edge> kruskalsAlgorithm(vector<edge>graph,int vertices){
UnionFind uf(vertices);
vector<edge>spanningTree;
sort(graph.begin(),graph.end(),comparator);
spanningTree.push_back(graph[0]);
uf.merge(graph[0].src,graph[0].des);
for(int i=1;i<graph.size();i++){
if(!uf.connected(graph[i].src,graph[i].des)){
uf.merge(graph[i].src,graph[i].des);
spanningTree.push_back(graph[i]);
}
}
return spanningTree;
}
int32_t main(){
vector<edge>graph;
int e,v;
cin >> e >> v;
graph.resize(e);
for(int i=0;i<e;i++){
cin >> graph[i].src >> graph[i].des >> graph[i].weight;
}
vector<edge> spanningTree = kruskalsAlgorithm(graph,v);
for(edge x : spanningTree){
cout << x.src << " " << x.des << " " << x.weight << endl;
}
return 0;
}