Find the Minimum spanning tree of the graph
Example:
Input: n=4, m=5,edges={{1,2,5},{2,3,3},{3,1,4},{1,4,2},{4,3,6}}
Output:
MST Edges1 4 22 3 33 1 4MST Cost9
Approach:
C++
#include <bits/stdc++.h>using namespace std;//structure of edge//i.e a->b with weight wstruct Edge{int a,b,w;};Edge arr[1000001];//array of parent of//each nodesint parent[100001];//array to have size of//the setint size1[100001];//make the setvoid make_set(int n){for(int i=1;i<=n;i++){parent[i]=i;size1[i]=1;}}//find in which set//the particular element//is presentint find(int a){if(a==parent[a])return a;return parent[a]=find(parent[a]);}//union of 2 setsvoid union_set(int a,int b){a=find(a);b=find(b);if(a!=b){if(size1[a]<size1[b])swap(a,b);parent[b]=a;size1[a]+=size1[b];}}//comparator used to//sort the edges by the weightsbool cmp(Edge a,Edge b){return a.w<b.w;}void KrushkalSAlgorithm(int m){//variable to hold the//cost of MSTint MSTCost=0;//vector to hold the//which edges are into the MSTvector<Edge> res;//sort the edges according//to the weightssort(arr,arr+m,cmp);//iterate for all the edgesfor(int i=0;i<m;i++){//fisrt point of edgeint a=arr[i].a;//last point of edgeint b=arr[i].b;//find in which sets they are belongsa=find(a);b=find(b);//if both are in different setsif(a!=b){//use this edge into MSTMSTCost+=arr[i].w;//add this edge into MST edgeEdge e;e.a=arr[i].a;e.b=arr[i].b;e.w=arr[i].w;res.push_back(e);//make unionunion_set(a,b);}}//print the edges which are into//the MST of the graphcout<<"MST Edges\n";for(Edge e:res){cout<<e.a<<" "<<e.b<<" "<<e.w<<"\n";}//print the cost of MSTcout<<"MST Cost\n";cout<<MSTCost<<"\n";}int main(){int n=4;int m=5;make_set(n);//add edges first edgearr[0].a=1; arr[0].b=2; arr[0].w=5;//second edgearr[1].a=2; arr[1].b=3; arr[1].w=3;//third edgearr[2].a=3; arr[2].b=1;arr[2].w=4;//4th edgearr[3].a=1; arr[3].b=4;arr[3].w=2;//5th edgearr[4].a=4; arr[4].b=3; arr[4].w=6;KrushkalSAlgorithm(m);return 0;}//Time Complexity: O(mlog(n))
No comments:
Post a Comment