#include #include #include #include #include #include #include #include using namespace std; typedef long long LL; const int maxn = 5005; const int INF = 0x7FFFFFFF; int T, n, m, fa[maxn]; struct point { int x, y, cost; void read(){ scanf("%d%d%d", &x, &y, &cost); } bool operator<(const point&a)const{ return cost < a.cost; }; }a[maxn * 10]; int get(int x) { return fa[x] == x ? fa[x] : fa[x] = get(fa[x]); } int main(){ scanf("%d", &T); while (T--) { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) a[i].read(); sort(a, a + m); int ans = INF; for (int i = 0; i < m; i++) { int cnt = n - 1, res; for (int j = 1; j <= n; j++) fa[j] = j; for (int j = i; j < m; j++) { int fx = get(a[j].x), fy = get(a[j].y); if (fx == fy) continue; else fa[fx] = fy; if (!(--cnt)) { res = a[j].cost - a[i].cost; break; } } if (cnt) break; ans = min(ans, res); } if (ans == INF) printf("-1\n"); else printf("%d\n", ans); } return 0; }