Skip to content

Commit 6efccb5

Browse files
authored
Merge pull request csubhasundar#173 from Prekshya12/main
Create Kruskal.cpp
2 parents 5581875 + aed2a18 commit 6efccb5

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

c++/Kruskal.cpp

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Edge
5+
{
6+
public:
7+
int source;
8+
int destination;
9+
int weight;
10+
11+
};
12+
13+
bool compare(Edge e1,Edge e2)
14+
{
15+
return (e1.weight<e2.weight);
16+
}
17+
18+
int find(int v,int *parents)
19+
{
20+
if(parents[v]==v)
21+
{
22+
return v;
23+
}
24+
return find(parents[v], parents);
25+
}
26+
27+
bool Union(Edge *output,Edge *input,int v,int *parents)
28+
{
29+
int count=0,i=0;
30+
while(count<v-1)
31+
{
32+
int parentS=find(input[i].source,parents);
33+
int parentD=find(input[i].destination,parents);
34+
if(parentS!=parentD)
35+
{
36+
output[count]=input[i];
37+
count++;
38+
parents[parentS]=parents[parentD];
39+
}
40+
i++;
41+
}
42+
}
43+
44+
int main() {
45+
// Write your code here
46+
int v,e;
47+
cin>>v>>e;
48+
Edge *input=new Edge[e];
49+
for(int i=0;i<e;i++)
50+
{
51+
cin>>input[i].source>>input[i].destination>>input[i].weight;
52+
}
53+
54+
sort(input,input+e,compare);
55+
56+
int *parents=new int[v];
57+
for(int i=0;i<v;i++)
58+
{
59+
parents[i]=i;
60+
}
61+
Edge *output=new Edge[v-1];
62+
Union(output,input,v,parents);
63+
64+
for(int i=0;i<v-1;i++)
65+
{
66+
cout<<min(output[i].source,output[i].destination)<<" "<<max(output[i].source,output[i].destination)<<" "<<output[i].weight<<endl;
67+
}
68+
}

0 commit comments

Comments
 (0)