The minimum spanning tree--kruskal algorithm for graphs

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.