The process of Kruskal algorithm: (1) The whole edge is sorted by weight from small to large. (2) in order (edge right from small to large order) consider no edge, as long as this side and we have selected side steps to form a circle, the edge is retained, otherwise give up this edge.
The algorithm succeeds in selecting (N-1) the edge, forming a minimum spanning tree, of course, if the algorithm cannot select the (n-1) edge, then the original image is not connected. The path in the figure is sorted by the size of the weights as AF 1;be 4; BD 5; BC 6;dc:10; BF 11;DF 14; AE 16; AB 17; EF 33; The process of the algorithm is selected as follows: A,f is not in a collection, so choose AF. E,d is not in a collection, you can choose B,d is not in a collection, optional bdb,c is not in a collection, optional bcb,d in the same set, discard BD, choose bf to all the vertices are connected, the algorithm end =; U[i],v[i] respectively storage vertex, W[i] Save the weight value, Use r[i] to indicate the ordinal of an edge here the order of the weights can be written like this
1 BOOL cmp (int i,int j)2{3 return W[i] <W[j]; 4 }5 sort (r,r+m,cmp);
Then we need to consider whether the newly added edge will form a ring with the previously selected edge, that is, to determine if the u,v is in the same connected component, here we use the set to find, and then merge
F[x] represents X, merging requires only a single statement f[x]=y;. The code for implementing the Kruskal algorithm is then as follows
1#include <stdio.h>2#include <string.h>3#include <iostream>4#include <algorithm>5 using namespacestd;6 #defineMAXN 50007 intF[MAXN];8 intU[MAXN],V[MAXN],W[MAXN],R[MAXN];9 intn,m;Ten BOOLcmpintIintj) One { A returnw[i]<W[j]; - } - intFindintx) the { - returnF[x]==x?X:find (f[x]); - } - __int64 Kruskal () + { -__int64 ans=0; + for(intI=1; i<=n;i++) A { atf[i]=i; - } - for(intI=1; i<=m;i++) - { -r[i]=i; - } inSort (r+1, r+m+1, CMP); - for(intI=1; i<=m;i++) to { + intE=R[i]; - intx=find (U[e]); the inty=find (V[e]); * if(x!=y) $ {Panax Notoginsengans+=W[e]; -f[x]=y; the } + } A returnans; the } + intMain () - { $ while(~SCANF ("%d", &n) &&N) $ { -Memset (R,0,sizeof(R)); - //memset (u,0,sizeof (u)) them=n* (n1)/2; - for(intI=1; i<=m;i++)Wuyi { thescanf" %d%d%d",&u[i],&v[i],&w[i]); - } Wuprintf"%lld\n", Kruskal ()); - } About}
Minimum spanning Tree Kruskal (Kruskal) algorithm to find the minimum spanning tree