//UVA1395SlimSpan
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int INF = 1000000000;
const int maxn = 100000 + 10;
int n;
struct Edge {
int u, v, w;
Edge(int u, int v, int w) : u(u), v(v), w(w) {}
bool operator < (const Edge& rhs) const {
return w < rhs.w;
}
};
vector<Edge> edges;
int p[maxn];
int Find(int u) {
return p[u] == u ? u : Find(p[u]);
}
int solve() {
int m = edges.size();
//printf("m = %d\n", m);
int ans = INF;
sort(edges.begin(), edges.end());//让边有序化,便于ans值的更新
for(int L = 0; L < m; L++) {
for(int i = 1; i <= n; i++) p[i] = i;//让各个点自成连通分量
int cnt = n;
for(int R = L; R < m; R++) {
int x = Find(edges[R].u), y = Find(edges[R].v);//找寻祖先
if(x != y) {//不在一个连通分量里
p[x] = y;
//printf("cnt = %d\n", cnt);
if(--cnt == 1) ans = min(ans, edges[R].w - edges[L].w);
}
}
}
if(ans == INF) ans = -1;
return ans;
}
int main() {
int m;
while(scanf("%d%d", &n, &m) == 2 && n) {
edges.clear();
for(int i = 0; i < m; i++) {
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
edges.push_back(Edge(a, b, w));
}
printf("%d\n", solve());
}
return 0;
}
/*
4 5
1 2 3
1 3 5
1 4 6
2 4 6
3 4 7
4 6
1 2 10
1 3 100
1 4 90
2 3 20
2 4 80
3 4 40
2 1
1 2 1
3 0
3 1
1 2 1
3 3
1 2 2
2 3 5
1 3 6
5 10
1 2 110
1 3 120
1 4 130
1 5 120
2 3 110
2 4 120
2 5 130
3 4 120
3 5 110
4 5 120
5 10
1 2 9384
1 3 887
1 4 2778
1 5 6916
2 3 7794
2 4 8336
2 5 5387
3 4 493
3 5 6650
4 5 1422
5 8
1 2 1
2 3 100
3 4 100
4 5 100
1 5 50
2 5 50
3 5 50
4 1 150
0 0
*/
UVA1395SlimSpan
最新推荐文章于 2022-10-09 23:28:27 发布