最小生成树最大边和最小边之差最小
题意:
求最小生成树最大边和最小边的最小差值
思路
用kruskal 算法,枚举最小边即可
代码
/*
* Author : Echo
* Email : 1666424499@qq.com
* Description :
* Created Time : 2017/10/10 19:25:26
* Last Modify : 2017/10/14 16:27:10
* File Name : \yanga11ang\write.cpp
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <queue>
using namespace std;
const int maxn=110;
const int maxm=1e4+100;
const double INF=1e9;
struct node{
int u,v,w;
}an[maxm];
int n,m;
int fa[maxn];
int findp(int a){
if(fa[a]==a) return a;
fa[a]=findp(fa[a]);
return fa[a];
}
int kruskal(int star){
for(int i=1;i<=n;i++){
fa[i]=i;
}
int cnt=0;
int maxx=-1e9,minn=1e9;
for(int i=star;i<=m;i++){
int u=an[i].u;
int v=an[i].v;
int up=findp(u);
int vp=findp(v);
if(up==vp) continue;
fa[up]=vp;
cnt++;
if(maxx<an[i].w) maxx=an[i].w;
if(minn>an[i].w) minn=an[i].w;
}
if(cnt!=n-1) return-1;
return maxx-minn;
}
bool cmp(node a,node b){
return a.w<b.w;
}
int main(){
while(~scanf("%d%d",&n,&m)){
if(n==m&&n==0)break;
for(int i=1;i<=m;i++){
scanf("%d%d%d",&an[i].u,&an[i].v,&an[i].w);
}
sort(&an[1],&an[1]+m,cmp);
int ans=1e9;
for(int i=1;i<=m;i++){
int res=kruskal(i);
if(res==-1) break;
if(ans>res) ans=res;
}
if(ans==1e9) printf("-1\n");
else printf("%d\n",ans);
}
return 0;
}
/*
*/