Repository navigation
Expand file tree
/
Copy pathKruskalMST.cpp
More file actions
110 lines (82 loc) · 1.65 KB
/
Copy pathKruskalMST.cpp
File metadata and controls
110 lines (82 loc) · 1.65 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <bits/stdc++.h>
using namespace std;
class edge{
public:
int src;
int dest;
int weight;
};
vector<edge> result;
int E;
int V;
edge* Edges=NULL;
int parent[105];
int ranks[105];
int finds(int a){
if(parent[a]!=a){parent[a] = finds(parent[a]);} // *
return parent[a];
}
void unions(int a,int b){
a=finds(a);
b=finds(b);
if(ranks[a]>ranks[b]){
parent[b]=a;
}
else
{
parent[a]=b;
if(ranks[a]==ranks[b]){ranks[b]++;}
}
return;
}
bool comparator1(edge a,edge b){
return (a.weight < b.weight);
}
void kruskalMST(){
sort(Edges, Edges+E, comparator1);
for(int i=0;i<E;i++){
int a=Edges[i].src;
int b=Edges[i].dest;
int parentA=finds(a);
int parentB=finds(b);
if(parentA!=parentB){
unions(parentA,parentB);
result.push_back(Edges[i]);
}
}
for(int i=0;i<result.size();i++){
cout<<result[i].src<<"----->"<<result[i].dest<<"\n";
}
return;
}
void init(){
for(int i=0;i<=V;i++){
parent[i]=i;
ranks[i]=1;
}
return;
}
int main(){
V=4;
E=5;
Edges=new edge[5];
Edges[0].src = 0;
Edges[0].dest = 1;
Edges[0].weight = 10;
Edges[1].src = 0;
Edges[1].dest = 2;
Edges[1].weight = 6;
Edges[2].src = 0;
Edges[2].dest = 3;
Edges[2].weight = 5;
Edges[3].src = 1;
Edges[3].dest = 3;
Edges[3].weight = 15;
Edges[4].src = 2;
Edges[4].dest = 3;
Edges[4].weight = 4;
init();
kruskalMST();
return 0;
}
// Time Complexity: O(ElogV)