#include #include #include #include using namespace std; const int N = 2005; const int M = 15005; struct Edge { int a, b, c; } E[M]; bool cmp(Edge P, Edge Q) { return P.c < Q.c; } struct DSU { int fa[N]; void init(int n = N - 1) { for(int i = 1; i <= n; i++) { fa[i] = i; } } int find(int x) { if(x == fa[x]) return x; return fa[x] = find(fa[x]); } void merge(int i, int j) { i = find(i); j = find(j); fa[i] = j; } bool same(int i, int j) { return find(i) == find(j); } } D; int solve(int n, int m, int i) { D.init(n); int j = i; int cnt = 0; int last = -1; for(; i < m && cnt < n - 1; i++) { if(D.same(E[i].a, E[i].b)) continue; D.merge(E[i].a, E[i].b); cnt++; last = i; } if(cnt == n - 1) { return E[last].c - E[j].c; } else { return -1; } } int main() { //freopen("in.txt", "r", stdin); int T, n, m; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &m); for(int i = 0; i < m; i++) { scanf("%d%d%d", &E[i].a, &E[i].b, &E[i].c); } sort(E, E + m, cmp); int ans = INT_MAX; for(int i = 0; i < m; i++) { int ret = solve(n, m, i); if(~ret) { ans = min(ans, ret); } else { break; } } if(ans == INT_MAX) { printf("-1\n"); } else { printf("%d\n", ans); } } return 0; }