【题意】
求一颗生成树,满足最大边和最小边之差最小
Input
The input consists of multiple datasets, followed by a line containing two zeros separated by a space.
Each dataset has the following format.
n m
a1 b1 w1
.
.
.
am bm wm
Every input item in a dataset is a non-negative integer. Items in a line are separated by a space.
n is the number of the vertices and m the number of the edges. You can assume 2 ≤ n ≤ 100 and
0 ≤ m ≤ n(n − 1)/2. ak and bk (k = 1, . . . , m) are positive integers less than or equal to n, which
represent the two vertices vak
and vbk
connected by the k-th edge ek. wk is a positive integer less than
or equal to 10000, which indicates the weight of ek. You can assume that the graph G = (V, E) is
simple, that is, there are no self-loops (that connect the same vertex) nor parallel edges (that are two
or more edges whose both ends are the same two vertices).
Output
For each dataset, if the graph has spanning trees, the smallest slimness among them should be printed.
Otherwise, ‘-1’ should be printed. An output should not contain extra characters.
Sample Input
4 5
1 2 3
1 3 5
1 4 6
2 4 6
3 4 7
4 6
1 2 10
1 3 100
1 4 90
2 3 20
2 4 80
3 4 40
2 1
1 2 1
3 0
3 1
1 2 1
3 3
1 2 2
2 3 5
1 3 6
5 10
1 2 110
1 3 120
1 4 130
1 5 120
2 3 110
2 4 120
2 5 130
3 4 120
3 5 110
4 5 120
5 10
1 2 9384
1 3 887
1 4 2778
1 5 6916
2 3 7794
2 4 8336
2 5 5387
3 4 493
3 5 6650
4 5 1422
5 8
1 2 1
2 3 100
3 4 100
4 5 100
1 5 50
2 5 50
3 5 50
4 1 150
0 0
Sample Output
1
20
0
-1
-1
1
0
1686
50
【分析】
做完这道题你就变苗条了的意思。。
[沉迷打机,日渐消瘦。
正题->_->先把边排序,枚举最小边,然后就是让最长边最短了咯,就是最小瓶颈生成树,kruskal做最小生成树就好了。
复杂度:m^2
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#define INF 0xfffffff
#define Maxn 110 struct node
{
int x,y,c;
}t[Maxn*Maxn];
int n,m; bool cmp(node x,node y) {return x.c<y.c;}
int mymax(int x,int y) {return x>y?x:y;}
int mymin(int x,int y) {return x<y?x:y;} int fa[Maxn];
int ffa(int x)
{
if(fa[x]!=x) fa[x]=ffa(fa[x]);
return fa[x];
} int main()
{
while()
{
scanf("%d%d",&n,&m);
if(n==&&m==) break;
for(int i=;i<=m;i++) scanf("%d%d%d",&t[i].x,&t[i].y,&t[i].c);
sort(t+,t++m,cmp);
int cnt=,ans=INF;
for(int i=;i<=m;i++)
{
int cnt=;
for(int j=;j<=n;j++) fa[j]=j;
for(int j=i;j<=m;j++)
{
if(ffa(t[j].x)!=ffa(t[j].y))
{
fa[ffa(t[j].x)]=ffa(t[j].y);
cnt++;
}
if(cnt==n-) {ans=mymin(ans,t[j].c-t[i].c);break;}
}
}
if(ans==INF) printf("-1\n");
else printf("%d\n",ans);
}
return ;
}
跟LA3887不是一样的么,LA有毒啊狂wa。。蓝书的陈锋的代码也是wa的啊smg!!
2016-11-01 21:24:53