Minimum Spanning Tree + enumeration.
In an undirected graph, select the minimum "slim" value for all spanning trees.
"Slim" is defined to generate the edge with the largest weight value in the tree minus the value of the edge with the smallest weight value.
My idea is to sort, and then from 0 ~ M enumeration. The edge of the enumeration must be added each time.
Then, select and add edges to the left and right sides. If a spanning tree is formed, INF cannot be returned.
In fact, I think my code is a bit problematic. I don't know who is closer to the enumeration side. We have prepared for WA, but we did not expect AC.
#include<cstdio>#include<cstring>#include<string>#include<queue>#include<algorithm>#include<queue>#include<map>#include<stack>#include<iostream>#include<list>#include<set>#include<cmath>#define INF 0x7fffffff#define eps 1e-6using namespace std;int n,m;int fa[101];struct lx{ int u,v,len;}l[5001];bool cmp(lx a,lx b){ return a.len<b.len;}int father(int x){ if(x!=fa[x]) return fa[x]=father(fa[x]);}int Kruskal(int j){ int ans=0; int maxv,minv; int num=2; for(int i=1;i<=n;i++) fa[i]=i; int x=father(l[j].u); int y=father(l[j].v); fa[y]=x; maxv=minv=l[j].len; int i=1,L,R; while(num<n) { bool flagl=0,flagr=0; L=j-i,R=j+i; if(L>=0&&L<m)flagl=1; if(R>=0&&R<m)flagr=1; int fu,fv; if(flagl) { fu=father(l[L].u); fv=father(l[L].v); if(fu!=fv) { fa[fv]=fu; minv=l[L].len; num++; } if(num>=n)break; } if(flagr) { fu=father(l[R].u); fv=father(l[R].v); if(fu!=fv) { fa[fv]=fu; maxv=l[R].len; num++; } if(num>=n)break; } i++; if(!flagl&&!flagr)return INF; } return max(maxv,minv)-min(maxv,minv);}int main(){ while(scanf("%d%d",&n,&m),n||m) { for(int i=0;i<m;i++) scanf("%d%d%d",&l[i].u,&l[i].v,&l[i].len); sort(l,l+m,cmp); int ans=INF; for(int i=0;i<m;i++) { ans=min(ans,Kruskal(i)); } if(ans==INF)puts("-1"); else printf("%d\n",ans); }}