题意:给出一个n个结点的图,求最大边减去最小边尽量小的生成树。
思路:暴力最小的边,用Kruskal求最小生成树,维护最大边减去最小边的最小值
#include <iostream>
#include <cstdio>
#include <algorithm>
const int INF = 0x3f3f3f3f;
using namespace std;
int pre[105],u[105 * 105],v[105 * 105],w[105 * 105],r[105 * 105];
int cmp(const int i,const int j){
return w[i] < w[j];
}
int find(int x){
return x == pre[x] ? x : pre[x] = find(pre[x]);
}
int join(int x,int y){
int fx = find(x);
int fy = find(y);
if(fx != fy){
pre[fy] = fx;
return 1;
}
return 0;
}
int main(void){
int n,m;
while(scanf("%d%d",&n,&m) != EOF ){
if(n == 0 && m == 0){
break;
}
int a,b,c;
for(int i = 0; i < m; i++){
scanf("%d%d%d",&a,&b,&c);
u[i] = a;
v[i] = b;
w[i] = c;
r[i] = i;
}
sort(r,r + m,cmp);
int ans = INF;
for(int i = 0; i < m; i++){
for(int j = 1; j <= n; j++){
pre[j] = j;
}
int cnt = 0;
int Max;
for(int k = i; k < m; k++){
int e = r[k];
int uu = u[e];
int vv = v[e];
if(join(uu,vv)){
cnt++;
}
if(cnt == n - 1){
Max = w[e];
break;
}
}
if(cnt == n - 1){
ans = min(ans,Max - w[r[i]]);
}
}
if(ans >= INF){
printf("-1\n");
}
else{
printf("%d\n",ans);
}
}
return 0;
}