思路:
我们发现n<=100,所以直接暴力
c o d e code code
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int t;
int n, m, fa[110];
int head[110];
struct node {
int from, to, w;
}b[10000];
bool cmp(node x, node y) {
return x.w < y.w;
}
int getfa(int x) {
if(x == fa[x]) return x;
return fa[x] = getfa(fa[x]);
}
int main() {
scanf("%d", &t);
while(t --) {
int ans = 1e9;
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i ++) scanf("%d%d%d", &b[i].from, &b[i].to, &b[i].w);
sort(b + 1, b + 1 + m, cmp);
for(int i = 1; i <= m; i ++) {
int k = 0;
for(int j = 1; j <= n; j ++) fa[j] = j;
for(int j = i; j <= m; j ++) {
int x = b[j].from, y = b[j].to;
int xx = getfa(x), yy = getfa(y);
if(xx == yy) continue;
fa[xx] = yy;
k ++;
if(k == n - 1) {
ans = min(b[j].w - b[i].w, ans);
break;
}
}
}
if(ans == 1e9) printf("-1\n");
else printf("%d\n", ans);
}
}