// C++ program for Kruskal's algorithm to find Minimum
// Spanning Tree of a given connected, undirected and
// weighted graph
#include<bits/stdc++.h>
usingnamespacestd;
// Creating shortcut for an integer pair
typedefpair<int,int>iPair;
// Structure to represent a graph
structGraph
{
intV,E;
vector<pair<int,iPair>>edges;
// Constructor
Graph(intV,intE)
{
this->V=V;
this->E=E;
}
// Utility function to add an edge
voidaddEdge(intu,intv,intw)
{
edges.push_back({w,{u,v}});
}
// Function to find MST using Kruskal's
// MST algorithm
intkruskalMST();
};
// To represent Disjoint Sets
structDisjointSets
{
int*parent,*rnk;
intn;
// Constructor.
DisjointSets(intn)
{
// Allocate memory
this->n=n;
parent=newint[n+1];
rnk=newint[n+1];
// Initially, all vertices are in
// different sets and have rank 0.
for(inti=0;i<=n;i++)
{
rnk[i]=0;
//every element is parent of itself
parent[i]=i;
}
}
// Find the parent of a node 'u'
// Path Compression
intfind(intu)
{
/* Make the parent of the nodes in the path
from u--> parent[u] point to parent[u] */
if(u!=parent[u])
parent[u]=find(parent[u]);
returnparent[u];
}
// Union by rank
voidmerge(intx,inty)
{
x=find(x),y=find(y);
/* Make tree with smaller height
a subtree of the other tree */
if(rnk[x]>rnk[y])
parent[y]=x;
else// If rnk[x] <= rnk[y]
parent[x]=y;
if(rnk[x]==rnk[y])
rnk[y]++;
}
};
/* Functions returns weight of the MST*/
intGraph::kruskalMST()
{
intmst_wt=0;// Initialize result
// Sort edges in increasing order on basis of cost
sort(edges.begin(),edges.end());
// Create disjoint sets
DisjointSetsds(V);
// Iterate through all sorted edges
vector<pair<int,iPair>>::iteratorit;
for(it=edges.begin();it!=edges.end();it++)
{
intu=it->second.first;
intv=it->second.second;
intset_u=ds.find(u);
intset_v=ds.find(v);
// Check if the selected edge is creating
// a cycle or not (Cycle is created if u
// and v belong to same set)
if(set_u!=set_v)
{
// Current edge will be in the MST
// so print it
cout<<u<<" - "<<v<<endl;
// Update MST weight
mst_wt+=it->first;
// Merge two sets
ds.merge(set_u,set_v);
}
}
returnmst_wt;
}
// Driver program to test above functions
intmain()
{
/* Let us create above shown weighted
and undirected graph */
intV=9,E=14;
Graphg(V,E);
// making above shown graph
g.addEdge(0,1,4);
g.addEdge(0,7,8);
g.addEdge(1,2,8);
g.addEdge(1,7,11);
g.addEdge(2,3,7);
g.addEdge(2,8,2);
g.addEdge(2,5,4);
g.addEdge(3,4,9);
g.addEdge(3,5,14);
g.addEdge(4,5,10);
g.addEdge(5,6,2);
g.addEdge(6,7,1);
g.addEdge(6,8,6);
g.addEdge(7,8,7);
cout<<"Edges of MST are \n";
intmst_wt=g.kruskalMST();
cout<<"\nWeight of MST is "<<mst_wt;
return0;
}