The main idea: to define the difference between the maximum and the minimum edges of the graph spanning tree is to slim, to find the slender degree of the smallest tree.
Title Analysis: First, all the edges are ordered from small to large, in the continuous interval [l,r] in the edge if it can form a spanning tree, then this tree must have the smallest degree of thinness. Enumerate all of these intervals.
The code is as follows:
# include<iostream># include<cstdio># include<set># include<queue># include<cstring># Include<algorithm>using namespace std;# define REP (i,s,n) for (int i=s;i<n;++i) # define CL (A, B) memset (A, B, sizeof (a)) # define CLL (A,b,n) Fill (a,a+n,b) const int N=105;CONST int inf=1<<30;struct edge{int u,v,w; BOOL operator < (const Edge &a) Const {return w<a.w; }}; Edge e[5005];int fa[n],n,m;int Findfa (int u) {if (fa[u]!=u) return Fa[u]=findfa (Fa[u]); return u;} BOOL Judge () {int cnt=0; REP (i,1,n+1) if (fa[i]==i) ++cnt; return cnt==1;} int main () {//freopen ("UVALive-3887 Slim Span.txt", "R", stdin); while (scanf ("%d%d", &n,&m) && (n+m)) {REP (i,0,m) scanf ("%d%d%d", &e[i].u,&e[i].v,&e[i]. W); Sort (e,e+m); int ans=inf; Rep (L,0,m) {rep (i,1,n+1) fa[i]=i; REP (r,l,m) {int u=e[r].u,v=e[r].v; int A=findfa (u); int B=findfa (v); if (a!=b) fa[a]=b; if (judge ()) {ans=min (ANS,E[R].W-E[L].W); Break }}} if (Ans==inf) printf (" -1\n"); else printf ("%d\n", ans); } return 0;}
UVALive-3887 Slim Span (Kruskal)