先將邊權從小到大排序,然後對於邊權集合,若此時的邊權集合足以構成一棵樹,那就記錄答案:
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define rep(i,x,y) for(ll i=(x);i<=(y);i++)
#define repl(i,x,y) for(ll i=(x);i<(y);i++)
#define repd(i,x,y) for(ll i=(x);i>=(y);i--)
using namespace std;
const ll N=1e4+5;
const ll Inf=1e18;
ll n,m,f[N];
struct node {
ll x,y,z;
}edge[N];
inline ll read() {
ll x=0;char ch=getchar();bool f=0;
while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
return f?-x:x;
}
ll find(ll x) {
return f[x]==x?x:f[x]=find(f[x]);
}
bool cmp(node p,node q) {
return p.z<q.z;
}
int main() {
// freopen("uva1395.txt","r",stdin);
while(true) {
n=read(),m=read();ll ans=Inf;
if(!n) return 0;
rep(i,1,m) edge[i].x=read(),edge[i].y=read(),edge[i].z=read();
if(n==2&&m==1) {
puts("0");continue;
}
sort(edge+1,edge+1+m,cmp);
rep(i,1,m) {
rep(j,1,n) f[j]=j;
ll mi=0,mx=0,cnt=0;
rep(j,i,m) {
ll x=edge[j].x;
ll y=edge[j].y;
ll z=edge[j].z;
ll fx=find(x),fy=find(y);
if(fx!=fy) {
cnt++;
f[fy]=fx;
if(cnt==1) mi=z;
if(cnt==n-1) {
mx=z;
break;
}
}
}
if(mi&&mx) ans=min(ans,mx-mi);
}
if(ans==Inf) printf("-1\n");
else printf("%lld\n",ans);
}
return 0;
}