Kruskal Algorithm
One of the algorithms of the minimum spanning tree of graphs, using and checking the idea to find the minimum spanning tree.
The basic idea is to sort all the edges from small to large, traversing the edges in turn. If the two points connected by this edge are in a connected block, traverse the next edge, and if not, add this edge to the connected block so that the Benquan of the spanning tree can be minimized.
We use and check the set to determine whether the two points are in the same connected block, and if so, their find will be the same, otherwise not.
1#include <cstdio>2#include <algorithm>3 #defineN 420004 using namespacestd;5 structhehe{6 intA1;7 intB1;8 intC1;9 }edge[n];Ten intn,m,a,b,c,father[n],num,tot,k; One intcmp (hehe x,hehe y) { A returnx.c1<y.c1; - } - intFindintx) { the if(father[x]!=x) -father[x]=find (Father[x]); - returnFather[x]; - } + intMain () { -scanf"%d%d",&n,&m); + for(intI=1; i<=m;++i) { Ascanf"%d%d%d",&a,&b,&c); atedge[++num].a1=A; -edge[num].b1=b; -edge[num].c1=C; - } - for(intI=1; i<=n;++i) -father[i]=i; inSort (edge+1, edge+m+1, CMP); - for(intI=1; i<=m;++i) to if(Find (edge[i].a1)! =find (EDGE[I].B1)) { +father[edge[i].a1]=edge[i].b1; -tot+=edge[i].c1; thek++; * if(k==n-1) $ Break;Panax Notoginseng } -printf"%d", tot); the return 0; +}
View Code
The minimum spanning tree--kruskal algorithm for graphs