Description
某國有N個村子,M條道路,爲了實現“村村通工程”現在要”油漆”N-1條道路(因爲某些人總是說該國所有的項目全是從國外進口來的,只是漆上本國的油漆罷了),因爲“和諧”是此國最大的目標和追求,以致於對於最小造價什麼的都不在乎了,只希望你所選出來的最長邊與最短邊的差越小越好。
Input
第一行給出一個數字TOT,代表有多少組數據,Tot<=6
對於每組數據,首先給出N,M
下面M行,每行三個數a,b,c代表a村與b的村道路距離爲c.
Output
輸出最小差值,如果無解輸出”-1”.
Sample Input
1
4 5
1 2 3
1 3 5
1 4 6
2 4 6
3 4 7
Sample Output
1
Data Constraint
Hint
【樣例解釋】
選擇1-4,2-4,3-4這三條邊.
【數據範圍】
1:2 ≤ n ≤ 100 and 0 ≤ m ≤ n(n − 1)/2
2:每條邊的權值小於等於10000
3:保證沒有自環,沒有重邊
//written by zzy
題目大意:
求一顆最大邊-最小邊的值最小的生成樹
題解:
考慮暴力枚舉最小邊,跑最小生成樹,統計答案。
#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#define N 105
#define M 10005
#define Max 100000007
using namespace std;
int i,j,n,m,k,ans,p,u,tot;
int fa[N];
struct E{
int x,y,z;
}l[M];
bool cmp(E a,E b){
return a.z<b.z;
}
int get(int x) {
if (fa[x]==x) return x;
return fa[x]=get(fa[x]);
}
void merge(int x,int y) {
fa[get(y)]=get(x);
}
bool check()
{
int num=get(1);
for (int i=1;i<=n;i++)
if (get(i)!=num) return false;
return true;
}
int main()
{
scanf("%d",&tot);
for (u=1;u<=tot;u++)
{
ans=Max;
scanf("%d%d",&n,&m);
for (i=1;i<=m;i++)
scanf("%d%d%d",&l[i].x,&l[i].y,&l[i].z);
sort(l+1,l+m+1,cmp);
for (i=1;i<=m;i++)
{
for (k=1;k<=n;k++) fa[k]=k;
for (j=i;j<=m;j++)
if (get(l[j].x)!=get(l[j].y))
{
merge(l[j].x,l[j].y);
p=j;
}
if (check()) ans=min(ans,l[p].z-l[i].z);
}
if (ans!=Max) printf("%d\n",ans);
else printf("%d\n",-1);
}
}