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