(* ^ - ^ *) hope Gangster pointing problem solution of konjac (* ^ __ ^ *)
I personally think that this question is the template title Kruskal algorithm is quite simple .
The Kruskal (Kruskal) : using an ingenious disjoint-set to the minimum spanning tree algorithm.
Implementation process:
Process is as follows:
- Initialization, initialize the disjoint-set, each point of the parent node for itself.
- Counter to zero.
- All right edge of the value of small to large fast row.
- Specific Kruskal's algorithm:
1 for(int i=1;i<=m;i++) 2 { 3 int f1=Find(e[i].x),f2=Find(e[i].y); 4 if(f1!=f2) 5 { 6 ans=max(ans,e[i].dis); 7 fa[f1]=f2; 8 if(k==n-1) break; 9 k++; 10 } 11 }
Full code below (comment Diudiu a)
code
#include <bits / STDC ++ H.> the using namespace STD; int n-, m, ANS, K = . 1 , FA [ 100005 ]; struct Node // represented by edge structure { int X, Y, DIS; } E [ 100005 ]; BOOL CMP (Node x, Node Y) { return x.dis < y.dis; } int the Find ( int x) // find the ancestors of x { IF FA [x] = (FA [x] = x!) the Find (FA [X]); return FA [X]; } void of Union ( int X, int y)//将x,y并为一个集合 { if(Find(x)!=Find(y)) fa[Find(x)]=Find(y); } int main() { cin>>n>>m; for(int i=1;i<=n;i++) fa[i]=i; for(int i=1;i<=m;i++) cin>>e[i].x>>e[i].y>>e[i].dis; sort(e+1,e+m+1,cmp);//快排 for(int I = . 1 ; I <= m; I ++ ) { int F1 = the Find (E [I] .x), F2 = the Find (E [I] .y); IF ! (F1 = F2) // if different fathers { ANS = max (ANS, E [I] .dis); // update answer FA [F1] = F2; IF (K == N- . 1 ) BREAK ; // least sides connected points -1 K ++; // counter ++ } } COUT << ANS << endl; // output return 0 ; }