#include <bits/stdc++.h> using namespace std; #define N 105 #define INF 0x7ffffff struct Edge { int u; int v; int w; }edge[N*N/2]; int n, m, span, p[N], rank[N]; int cmp(Edge a, Edge b) { return a.w<b.w; } int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); } void unionSet(int x, int y) { if (rank[x] > rank[y]) p[y] = x; else { p[x] = y; if (rank[x] == rank[y]) rank[y]++; } } void kruskal() { sort(edge+1, edge+m+1, cmp); for(int i=1; i<=m-n+2; i++) { int cnt = 0; int start = 0; for(int j=1; j<=n; j++) p[j] = j; memset(rank, 0, sizeof(rank)); for(int k=i; k<=m; k++) { int x = find(edge[k].u); int y = find(edge[k].v); if(x != y) { unionSet(x,y); cnt++; if(!start) start = i; if(cnt == n-1) { span = min(span, edge[k].w-edge[start].w); break; } } } } if(span == INF) cout<<-1<<endl; else cout<<span<<endl; } int main() { while(~scanf("%d%d",&n, &m) && n+m) { for(int i=1; i<=m; i++) cin>>edge[i].u>>edge[i].v>>edge[i].w; span = INF; kruskal(); } return 0; }
时间: 2024-11-10 07:48:09