You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.3 KiB
C++

#define _CRT_SECURE_NO_WARNINGS
#define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING
#include <bits/stdc++.h>
using namespace std;
template <int N>
struct DisJointSet
{
int f[N], rk[N];
int find(int x) { return f[x] == x ? x : f[x] = find(f[x]); }
void link(int x, int y)
{
if (rk[x] > rk[y]) swap(x, y);
f[x] = y, rk[y] = max(rk[y], rk[x] + 1);
}
void reset()
{
for (int i = 0; i < N; i++) f[i] = i;
memset(rk, 0, sizeof(rk));
}
};
struct edge
{
int f, t, l;
bool operator<(const edge &rhs) const { return l < rhs.l; }
};
edge E[105 * 105 / 2];
int main()
{
DisJointSet<105> U;
for (int n, m; scanf("%d%d", &n, &m), n | m;)
{
for (int i = 0; i < m; i++)
scanf("%d%d%d", &E[i].f, &E[i].t, &E[i].l);
sort(E, E + m);
unsigned ans = -1;
for (int i = 0; i < m; i++)
{
U.reset();
int cnt = 1;
unsigned tmp = -1;
for (int j = i; j < m && cnt < n; j++)
{
tmp = E[j].l - E[i].l;
int f1 = U.find(E[j].f), f2 = U.find(E[j].t);
if (f1 != f2) U.link(f1, f2), cnt++;
}
if (cnt == n) ans = min(ans, tmp);
}
printf("%d\n", ans);
}
return 0;
}