Kruscal Algorithm Description:
The idea of the kruscal algorithm is: At first, all nodes are considered as isolated collections, and all the edges in the graph are sorted from small to large, then the edges are traversed, and if the two endpoints of the edge are in two different sets, the two sets that belong to the end of the edge are merged, Until the N-1 bar is selected, all n nodes in the graph are merged into the same set, and the n-1 merge selects the n-1 edge, which is the smallest spanning tree of the graph that we need, consisting of the n-1 edge and the N-brother node on the graph.
The performance of Kruscal algorithm relies on the number of edges, so the kruscal algorithm is superior to the minimum spanning tree problem of sparse graphs.
My Code:
1#include <iostream>2#include <vector>3#include <algorithm>4 5 using namespacestd;6 7 #defineMAXN 1000058 #defineINF 0x7fffffff9 Ten structEdge One { A intu, V, W; -Edgeint_u,int_v,int_w): U (_u), V (_v), W (_w) {} - BOOL operator< (ConstEdge &x)Const the { - returnw<X.W; - } - }; + -Vector<edge>e; + intN, M; A at structUnionfindset - { - intST[MAXN]; - voidInit () - { - for(intI=1; i<=n; ++i) St[i] =i; in } - intFindset (intx) to { + if(X==st[x])returnx; - returnST[X] =Findset (st[x]); the } * voidUnionset (intXinty) $ {Panax Notoginseng intSX = Findset (x), sy =Findset (y); -ST[SX] =Sy; the } + }ufs; A the intkruscal () + { - sort (E.begin (), E.end ()); $ intAns =0, cnt =0; $ ufs.init (); - for(intI=0; I<e.size () &&cnt<n-1; ++i) - { the intSu = Ufs.findset (e[i].u), SV =Ufs.findset (E[I].V); - if(su!=SV)Wuyi { the Ufs.unionset (su, SV); -Ans + =E[I].W; Wu } - } About returnans; $ } - - intMain () - { A while(cin>>n>>m) + { the e.clear (); - while(m--) $ { the intu, V, W; theCin>>u>>v>>W; the E.push_back (Edge (U, V, W)); the } -Cout<<kruscal () <<Endl; in } the return 0; the}
Title Link: http://hihocoder.com/problemset/problem/1098
hihocoder1098 minimum Spanning tree (kruscal algorithm)