Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

C++ Program to find Minimum Spanning Tree using Kruskal Algorithm

Article Creation Date : 20-Jun-2021 03:29:20 AM

Description:

Spanning Tree:

 A spanning tree is a subset of Graph G, which has all the vertices covered
with minimum possible number of edges.
 A spanning tree does not have cycles and it cannot be disconnected.

Minimum Spanning Tree:

 In a weighted graph, a minimum spanning tree is a spanning tree that has


minimum weight than all other spanning trees of the same graph.
 A minimum spanning tree has (V - 1) edges where V is the number of
vertices in the given graph.

There are two algorithms for finding minimum spanning tree:

1. Kruskal's Algorithm
2. Prim's Algorithm

Both are greedy algorithms. In this article, we will see the implementation of
Kruskal's Algorithm.

Kruskal's Algorithm:
1. Sort all the edges in increasing order of their weight.
2. Pick the smallest edge. Check if it forms a cycle with the spanning tree
formed so far.
If cycle is not formed, include this edge. Else, discard it.
3. Repeat step 2 until there are (V-1) edges in the spanning tree.

Code:
/*Kruskal Algorithm to find minimum spanning tree (in
undirected
graph)
(Cycle detection using Union find Algorithm)*/

#include <bits/stdc++.h>
using namespace std;

class Edge{
public:
int src;
int dest;
int wt;
};

bool compare(Edge e1,Edge e2){


return e1.wt<e2.wt;
}

int getParent(int v,int parent[]){


if(parent[v]==v){
return v;
}
return getParent(parent[v],parent);
}

int main()
{
int n,E;
cin>>n>>E;
Edge edges[E];
for(int i=0;i<E;i++){
cin>>edges[i].src>>edges[i].dest>>edges[i].wt;
}

//Kruskal algo

//sorted the edges array in increasing order


sort(edges,edges+E,compare);

Edge output[n-1];

//Union find algorithm to detect cycle


int parent[n];
for(int i=0;i<n;i++){
parent[i]=i;
}
int count=0;
int i=0;
while(count<n-1){
Edge currentEdge=edges[i];
int p1=getParent(currentEdge.src,parent);
int p2=getParent(currentEdge.dest,parent);
if(p1!=p2){
output[count]=currentEdge;
count++;
parent[p1]=p2;
}
i++;
}

//Printing the MST


for(int i=0;i<n-1;i++){
if(output[i].src<output[i].dest){
cout<<output[i].src<<" "<<output[i].dest<<" "<<output
[i].wt<<endl;
}
else cout<<output[i].dest<<" "<<output[i].src<<" "<<outpu
t[i].wt<<endl;
}

return 0;
}

Input:
4 4
0 1 3
0 3 5
1 2 1
2 3 8
Output:
1 2 1
0 1 3
0 3 5

You might also like