The Kruskal algorithm is to sort all the edge weights in the graph, and then from the smallest Benquan value to find, connect the points in the graph, when the weight of the edge is small, but the connection in the way after the formation of the loop when the side is discarded, looking for the next side, and so on, false with n points, you only need to find n-1 edge
#include <stdio.h>#include<iostream>#include<algorithm>#include<string.h>using namespacestd;Const intmaxn= +;intv,l;///v represents the number of points, L represents the number of edgesintFA[MAXN],SON[MAXN];structkruskal{///the distance between the storage point and the two points of the structure.intb;intvalue;} EDGE[MAXN];BOOLCMP (Kruskal X,kruskal y) {///arrange the weights of the edges in order from small to largereturnx.value<Y.value;}intFinintX///finding the root node of x{ returnFa[x]==x?Fa[x]:fin (fa[x]);}BOOLUnin (intXinty) { intRoot1,root2; ROOT1=fin (x); Root2=fin (y); if(root1==Root2) { return false;///returns False when the input two points have the same root node when the ring is formed . } Else if(son[root1]>=Son[root2]) {Fa[root2]=ROOT1;///the root node of the Root2 is root1.SON[ROOT1]+=SON[ROOT2];///to connect a small tree to a large number of trees } Else{FA[ROOT1]=Root2; SON[ROOT2]+=SON[ROOT1]; } return true;///returns true as long as two points are not on the same root node.}intMain () {intN,total,sum,flag; CIN>>N; while(n--) {cin>>v>>l; Total=0; Sum=0; Flag=0; for(intI=1; i<=v;i++) {///Initializefa[i]=i; Son[i]=1; } for(intI=1; i<=l;i++) {cin>>edge[i].a>>edge[i].b>>Edge[i].value; } Sort (Edge+1, edge+1+L,CMP);///because Edge is starting from 1, so Edge is +1. for(intI=1; i<=l;i++){ if(Unin (edge[i].a,edge[i].b)) { Total++; Sum+=edge[i].value;///record the minimum weighted valuecout<<edge[i].a<<" -"<<edge[i].b<<Endl; } if(total==v-1){///there are N nodes that have n-1 to form the smallest spanning tree.flag=1; Break; } } if(flag) cout<<sum<<Endl; Elsecout<<"data error."<<Endl; } }
Minimum spanning Tree Kruskal algorithm