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:保证没有自环,没有重边
.
.
.
.
.
.
分析
先把边按长度排序,然后枚举最长边,再从大到小加边,直到实现连得边数为n-1,
最后加入的边即为此最长边对应的最短边。
之后再统计答案就好了
加边时用并查集维护。
.
.
.
.
.
.
程序:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int fa[200];
struct edge
{
int a,b,c;
} w[10000];
bool cmp(edge x,edge y)
{
return x.c>y.c;
}
int find(int x)
{
if (fa[x]==x) return x;
fa[x]=find(fa[x]);
return fa[x];
}
int main()
{
int tot;
scanf("%d",&tot);
while (tot--)
{
int n,m;
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
scanf("%d%d%d",&w[i].a,&w[i].b,&w[i].c);
sort(w+1,w+m+1,cmp);
int ans=2147483647;
for (int i=1;i<=m;i++)
{
for (int j=1;j<=n;j++)
fa[j]=j;
int tj=0;
for (int j=i;j<=m;j++)
{
int fx=find(w[j].a),fy=find(w[j].b);
if (fx!=fy)
{
fa[fx]=fy;
tj++;
if (tj==n-1)
{
ans=min(ans,w[i].c-w[j].c);
break;
}
}
}
}
if (ans==2147483647) printf("%d\n",-1); else printf("%d\n",ans);
}
return 0;
}