题目链接:https://vjudge.net/problem/UVA-1395
题意:这道题重新定义了最小生成树的含义是生成树中最小的边和最大的边的差值。然后给你一个无向带权图,让你输出最小生成树的值。若没有输出-1。
解题方法:简单稍微想一下就可以知道,我们只要枚举生成树中最小的那条边然后在这个基础上求最小生成树,这样每次更新最小值,最终就能得到答案。
代码如下:
//
//Created by BLUEBUFF 2016/1/29
//Copyright (c) 2016 BLUEBUFF.All Rights Reserved
//
#pragma comment(linker,"/STACK:102400000,102400000")
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//#include <ext/pb_ds/hash_policy.hpp>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <time.h>
#include <cstdlib>
#include <cstring>
#include <complex>
#include <sstream> //isstringstream
#include <iostream>
#include <algorithm>
using namespace std;
//using namespace __gnu_pbds;
typedef long long LL;
typedef unsigned long long uLL;
typedef pair<int, LL> pp;
#define REP1(i, a, b) for(int i = a; i < b; i++)
#define REP2(i, a, b) for(int i = a; i <= b; i++)
#define REP3(i, a, b) for(int i = a; i >= b; i--)
#define CLR(a, b) memset(a, b, sizeof(a))
#define MP(x, y) make_pair(x,y)
template <class T1, class T2>inline void getmax(T1 &a, T2 b) { if (b>a)a = b; }
template <class T1, class T2>inline void getmin(T1 &a, T2 b) { if (b<a)a = b; }
const int maxn = 60010;
const int maxm = 1e5+5;
const int maxs = 10;
const int maxp = 1e3 + 10;
const int INF = 1e9;
const int UNF = -1e9;
const int mod = 1e9 + 7;
const int rev = (mod + 1) >> 1; // NTT
//const double PI = acos(-1);
//head
struct edge{
int u, v, w;
edge(){}
edge(int u, int v, int w) : u(u), v(v), w(w){}
bool operator<(const edge &rhs) const{
return w < rhs.w;
}
void read(){
scanf("%d%d%d", &u, &v, &w);
}
}E1[10010], E2[10010];
int n, m, bas, fa[110];
void init(){
for(int i = 0; i < 110; i++) fa[i] = i;
}
int find_set(int x){
if(x == fa[x]) return x;
else return fa[x] = find_set(fa[x]);
}
int Kruskal(){
int cnt = 0, ret = 0;
for(int i = 0; i < m; i++){
if(E1[i].w < bas) continue;
int fx = find_set(E1[i].u), fy = find_set(E1[i].v);
if(fx == fy) continue;
fa[fx] = fy;
cnt++;
ret = max(ret, E1[i].w - bas);
if(cnt == n - 1) break;
}
if(cnt == n - 1) return ret;
else return INF;
}
int main(){
while(scanf("%d%d", &n, &m) == 2)
{
if(n == 0 && m == 0) break;
for(int i = 0; i < m; i++){
E1[i].read();
E2[i] = E1[i];
}
sort(E1, E1 + m);
int ans = INF;
for(int i = 0; i < m; i++){
bas = E2[i].w;
init();
ans = min(ans, Kruskal());
}
if(ans == INF) ans = -1;
printf("%d\n", ans);
}
return 0;
}