The main idea: to give you a graph of n points, to find the slim (maximum edge minus minimum) as small as possible spanning tree
Idea: Sort after the violent enumeration interval can be
//see if it explodes. int! array will not be one dimension less! //You must be careful about the conditions of the winning.#include <bits/stdc++.h>using namespacestd;#defineLL Long Long#defineAll (a) A.begin (), A.end ()#definePB Push_back#defineMk Make_pair#defineFi first#defineSe SecondConst intINF =0x3f3f3f3f;Const intMAXN = -+5;structedge{intu, V, Val; Edge (intU =0,intv =0,intval =0): U (U), V (v), Val (val) {}BOOL operator< (ConstEdge &a)Const{ returnVal <A.val; }}EDGES[MAXN*MAXN];intPAR[MAXN];intN, M;voidInit () { for(inti =1; I <= N; i++) Par[i] =i;}intPfind (intx) { if(Par[x] = = x)returnx; returnPAR[X] =Pfind (par[x]);}BOOLSolveintLintR) { for(inti = l; I <= R; i++){ intPU =Pfind (EDGES[I].U); intPV =Pfind (EDGES[I].V); if(PU = = PV)Continue; PAR[PU]=PV; } intp = Pfind (1); for(inti =2; I <= N; i++){ if(P! = Pfind (i))return false; } return true;}intMain () { while(SCANF ("%d%d", &n, &m) &&N) { for(inti =1; I <= m; i++) { intU, V, Val; scanf"%d%d%d", &u, &v, &val); Edges[i]=Edge (U, V, Val); } intAns =inf; Sort (Edges+1, edges + M +1); for(intL =1; L <= m; l++) {init (); for(intR = l; R <= m; r++){ if(Solve (L, R)) {ans= min (ans, edges[r].val-edges[l].val); Break; } } } if(ans = = inf) ans =-1; printf ("%d\n", ans); } return 0;}
View Code
Spanning tree with the lowest difference between the maximum and minimum sides UVA 1394