Graph theory-minimum spanning tree-kruskal algorithm

Source: Internet
Author: User

Related concepts:

Minimum spanning tree: in connected graph G, a tree that joins all vertices of the graph G with the smallest edge of the total weight

Ideas:first, the edge to the right from small to large sort, immediately after enumerating each edge, if the ancestor nodes of the two nodes are different (and check set), then connect to this edge, until the number of sides is equal to the node point-1 canadjacency matrix input, storage edge with class adjacency table
1#include <cstdio>2#include <algorithm>3 using namespacestd;4 #defineMaxn5 #defineMaxm6 intfather[maxn],n,m,cnt,ans,a,b;7 structnode8 {9     intU,v,val;Ten }EDGE[MAXM]; One intCMP (node A,node b) A { -     returna.val<B.val; - } the intFindintX//and check set + path compression - { -     if(father[x]==x)returnx; -     Else returnfather[x]=find (Father[x]); + } - intMain () + { Ascanf"%d",&n); at      for(intI=1; i<=n;i++) -father[i]=i; -      for(intI=1; i<=n;i++) -     { -          for(intj=1; j<=n;j++) -         { inscanf"%d",&a); -             if(a==0)Continue; toedge[++cnt].u=i; +edge[cnt].v=J; -Edge[cnt].val=A; the         } *     } $Sort (edge+1, edge+cnt+1, CMP);Panax Notoginsengm=CNT; -Cnt=1; the      for(intI=1; i<=m;i++) +     { AA=find (EDGE[I].U); theb=find (EDGE[I].V); +         if(a==b)Continue; -         Else//Connecting Edge $         { $father[b]=A; -cnt++; -ans+=Edge[i].val; the             if(cnt==n) Break; -         }Wuyi     } theprintf"%d", ans);//minimum spanning tree weights and -     return 0; Wu}
* Reference: Http://baike.baidu.com/link?url=kGlXMlnImpXrmDw8uojP7JDeRsPUoZE4YYXNvANyAnfp6cDaQRxkoGV5DY20BU2_ Zkkn5tf8ip-djte5nq2lfqhttp://baike.baidu.com/link?url=w9dudz7x1mt5n8865zflthxcyl_ Lhqu1gopn8lteijvanu-jo68el4oz6zbpmava

Graph theory-minimum spanning tree-kruskal algorithm

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.