A spanning tree of a connected graph is a connected, non-rings graph that contains all the vertices of the graph.
A minimum spanning tree of weighted connected graphs is a tree with the smallest weight of a graph, where the weight of the tree is defined as the sum of the weights of all sides.
The problem of minimum spanning tree is to find the minimum spanning tree problem of a given weighted connected graph.
The algorithm of minimum spanning tree mainly includes prim algorithm and Kruskal algorithm, this article mainly explains and realizes the latter.
The Kruskal algorithm is mainly based on the algorithm of the search set + greedy. At the beginning of the algorithm, all the edges are sorted in the non-descending order of the weights, then from an empty chart, scanning the ordered list, and attempting to add the next edge of the listing to the current sub-graph. However, if you add this edge to the loop, you skip the side of the line.
#include <iostream>#include<algorithm>using namespacestd;Const intn= Max;intFather[n],r[n],u[n],v[n],w[n];//define father for each node's father, R for each node number, u,v for node, and W for edge weightsintFindintX//and check the core algorithm of the set, looking for Father node{ intR=x; while(father[r]!=R) {R=Father[r]; } returnR;}BOOLcmpConst intAConst intb//used primarily to sort the weights of edges in the sort function{ returnw[a]<w[b];}intKruskal (intNintM//Core Algorithms{ intmst=0, cnt=0; for(intI=0; i<n;i++)//initialize each node's father for itself{Father[i]=i; } for(intI=0; i<m;i++)//record the ordinal of each edge{R[i]=i; } sort (R,r+M,CMP);//The edge according to the weight from small to large order, here only change the number, you can know which side for(intI=0; i<m;i++)//for each edge, it is judged whether the two vertices of the edge are connected and, if connected, prove that after joining, there will be loops, not considered { intE=R[i]; intx=find (U[e]); inty=find (V[e]); if(x!=y) {MST+=W[e]; FATHER[X]=y; CNT++; } } if(cnt<n-1)//prove that this diagram is not connected, there is no minimum spanning treemst=0; returnMST;}intMain () {intn,m; CIN>>n>>m; for(intI=0; i<m;i++) {cin>>u[i]>>v[i]>>W[i]; } intmst=Kruskal (n,m); if(mst==0) cout<<"The MST is not found"<<Endl; Elsecout<<"The MST is"<<mst<<Endl; return 0;}
Minimum spanning Tree-kruskal algorithm