forked from Saqib-Ahmad/hack-20
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkrushkalalgo.cpp
86 lines (69 loc) · 1.81 KB
/
krushkalalgo.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
#include<bits/stdc++.h>
using namespace std;
class DSU{
private:
int* leader;
int* size;
public:
DSU(int v){
leader=new int[v];
size=new int[v];
for(int i=0;i<v;i++){
leader[i]=-1;
size[i]=1;
}
}
int Find(int x){
if(leader[x] == -1){
return x;
}
return leader[x]=Find(leader[x]);
}
bool Union(int a,int b){
int leaderA=Find(a);
int leaderB=Find(b);
if(leaderA == leaderB){
return false;
}
if(size[leaderA] < size[leaderB]){
leader[leaderA]=leaderB;
size[leaderB]+=size[leaderA];
}else{
leader[leaderB]=leaderA;
size[leaderA]+=size[leaderB];
}
return true;
}
};
void kruskal(vector<vector<int>> edges,int n){
DSU dsu(n);
sort(edges.begin(),edges.end());
vector<vector<int>> tree;
for(int i=0;i<edges.size();i++){
int u=edges[i][1];
int w=edges[i][0];
int v=edges[i][2];
if(dsu.Union(u,v)){
tree.push_back({u,v,w});
}
}
for(auto edge: tree){
cout<<"( "<<edge[0]<<" , "<<edge[1]<<" , "<<edge[2]<<" ) , ";
}
cout<<"\n";
}
int main(){
cout<<"Please Enter the number of vertices and edges in your graph..\n";
int v,e;
cin>>v>>e;
//for Edge List Representation
vector<vector<int>> edges;
for(int i=0;i<e;i++){
int u,v,w;
cin>>u>>v>>w;
edges.push_back({w,u,v});
edges.push_back({w,v,u});
}
kruskal(edges,v);
return 0;
}