Few points, sort by edge weights, enumerate enumerations L and R, check connectivity. Once connected, update the answer.
Judge even General can O (1), before I was O (n) sentenced, previously written over, and later wrote T ...
#include <bits/stdc++.h>using namespacestd;Const intMAXN =101;Const intMaxe = maxn*maxn>>1;intn,m;intU[maxe],v[maxe],w[maxe];intPa[maxn];inlineBOOLcmpintAintb) {returnw[a]<w[b];}intR[maxe];inlinevoidIdxsort () { for(inti =0; I < m; i++) R[i] =i; Sort (R,r+m,cmp);}intFind (intx) {returnx==pa[x]?x:pa[x]=Find (pa[x]);}intCnt,ans;inlinevoidUnion (intAintb) { intS1 = Find (a), S2 =Find (b); if(S1! =S2) {PA[S1]= s2,cnt--; }}inlinevoidInitufs () { for(inti =1; I <= N; i++) Pa[i] = i; CNT = n1; }Const intINF =0x3f3f3f3f;intMain () {//freopen ("In.txt", "R", stdin); while(SCANF ("%d%d",&n,&m), N) { for(inti =0; I < m; i++) scanf ("%d%d%d", u+i,v+i,w+i); Idxsort (); Ans=INF; for(inti =0; I < m; i++) {initufs (); for(intj = i; J < M; J + +){ intR =R[j]; Union (U[r],v[r]); if(!CNT) {ans= Min (ans,w[r]-w[r[i]]); Break; }}} printf ("%d\n", ans==inf?-1: ans); } return 0;}
UVA UVA-1395 Slim Span