-
Notifications
You must be signed in to change notification settings - Fork 0
/
krushkal.cpp
67 lines (62 loc) · 1.47 KB
/
krushkal.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
#include<iostream>
#include<iomanip>
#include<algorithm>
using namespace std;
class Edges
{
public:int sources,dest,weights;
};
bool compare(Edges e1,Edges e2){
return e1.weights<e2.weights;}
int findParent(int v,int *parent)
{
if(parent[v]==v)
return v;
else
return(findParent(parent[v],parent));
}
void krushkal(Edges *input,int n,int E)
{
sort(input,input+E,compare);
Edges *output=new Edges[n-1];
int *parent = new int[n];
for(int i=0;i<n;i++)
{
parent[i]=i;
}
int count=0;
int i=0;
while(count !=n-1)
{
Edges CurrentEdge=input[i];
int sourceParent=findParent(CurrentEdge.sources,parent);
int destParent=findParent(CurrentEdge.dest,parent);
if(sourceParent!=destParent)
{
output[count]=CurrentEdge;
count++;
parent[sourceParent]=destParent;
}
i++;
}
for(int i=0;i<n-1;i++)
{
cout<<output[i].sources<<" "<<output[i].dest<<" "<<output[i].weights<<" "<<"\n";
}
}
int main()
{
int n,E;
cout<<"Enter Total No of Vertices :";
cin>>n;
cout<<"Enter Total Edges :";
cin>>E;
Edges *input=new Edges[E];
cout<<"Enter Values of source destination and weights of each edges";
for(int i=0;i<E;i++)
{
cin>>input[i].sources>>input[i].dest>>input[i].weights;
}
krushkal(input,n,E);
return 0;
}