boolmerge(int x, int y){ x = find(x); y = find(y); if (x == y) returnfalse; if (x != y) { fa[x] = y; returntrue; } }
boolkru(int st){ int cnt = 0; for (int i = 1; i <= n; i++) { fa[i] = i; } maxn = -inf; for (int i = st; i <= m; i++) { if (merge(e[i].a, e[i].b)) { maxn = e[i].v; cnt++; if (cnt == n - 1) returntrue; } } returnfalse; }
boolcmp(node a, node b){ return a.v < b.v; }
voidinit(){ for (int i = 1; i <= n; i++) fa[i] = i; sort(e + 1, e + m + 1, cmp); maxn = -inf; ans = inf; }
intmain(){ while (cin >> n) { cin >> m; if (!n && !m) break; for (int i = 1; i <= m; i++) { cin >> e[i].a >> e[i].b >> e[i].v; } init(); for (int i = 1; i <= m; i++) {//枚举最小的边 if (kru(i)) { ans = min(ans, maxn - e[i].v); } } if (ans == inf) cout << "-1\n"; else cout << ans << "\n"; } return0; }