MST: Kruskal's Algorithm

No comments

Kruskal's algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree for a connected weighted graph.
It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.
This algorithm needs to sort edges in non-decreasing order and uses a disjoint-set data structure to keep track which vertex is in which component.

Algorithm:Kruskal

MST-KRUSKAL(G,w) 1 A = φ 2. for each vertex 2 ∈ G:V 3. Make_set{} 4. Sort the edges in non-decreasing order by weight 5. for each edge(u,v) ∈ G,E is taken from non-decreasing order by weight 6. if(find_set(u)!=find_set(v) 7. A=A U {(u,v)} 8. Union(u,v) 9. return A

Here is the C++ implementation of Kruskal algorithm
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
#define edge pair< int,int >
vector< pair<int,edge> >G,MST;
int parent[MAX];
void reset(int n)
{
 G.clear();
 MST.clear();
 for(int i=0;i<=n;i++)
 parent[i]=i;
 
}
int find(int x)
{
 if(x!=parent[x])
 parent[x]=find(parent[x]);
 return parent[x];
}
int main()
{
 int n,e,u,v,w,pu,pv,total=0;
 cin>>n>>e;
 reset(n);
 for(int i=0;i<e;i++)
 {
  cin>>u>>v>>w;
  G.push_back(pair<int,edge >(w,make_pair(u,v)));// w(u,v) format
 }
 sort(G.begin(),G.end());    //sort will be done in increasing order of weight
 for(int i=0;i<e;i++)
 {
  pu=find(G[i].second.first); 
  pv=find(G[i].second.second);
  if((pu)!=(pv))
  {
   MST.push_back(G[i]);
   total+=G[i].first;
   parent[pu]=parent[pv];
  }
 }
 for(int i=0;i<MST.size();i++)
 {
  cout<<"("<<MST[i].second.first<<" "<<MST[i].second.second<<" ) :"<<MST[i].first<<endl;
 }
 cout<<"Mimimum cost for spanning tree is :"<<total<<endl;
}

No comments :