Test instructions
Find a spanning tree that satisfies the minimum difference between the maximum and minimum edges
Input
The input consists of multiple datasets, followed by a line containing and zeros separated by a space.
Each dataset has the following format.
Nm
A1 B1 W1
.
.
.
AM BM WM
Every input item in a dataset is a non-negative integer. Items in a line is 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) is positive integers less than or equal to N, which
represent the 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 this graph G = (V, E) is
Simple, that's, there is no self-loops (that connect the same vertex) nor parallel edges
Or more edges whose both ends is the same of both vertices).
Output
For each dataset, if the graph has spanning trees, the smallest slimness among them should is 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
Analysis
You'll get thinner after you finish the problem.
[Addicted to playing machine, gradually wasting.]
The topic->_-> first to sort, enumerate the smallest edge, and then let the longest edge of the shortest, is the smallest bottleneck spanning tree, Kruskal do the minimum spanning tree.
Complexity: m^2
1#include <cstdio>2#include <cstdlib>3#include <cstring>4#include <iostream>5#include <algorithm>6#include <queue>7 using namespacestd;8 #defineINF 0XFFFFFFF9 #defineMAXN 110Ten One structnode A { - intx,y,c; -}t[maxn*MAXN]; the intn,m; - - BOOLCMP (node X,node y) {returnx.c<y.c;} - intMymax (intXintY) {returnX>y?x:y;} + intMymin (intXintY) {returnX<y?x:y;} - + intFA[MAXN]; A intFFAintx) at { - if(fa[x]!=x) fa[x]=FFA (Fa[x]); - returnFa[x]; - } - - intMain () in { - while(1) to { +scanf"%d%d",&n,&m); - if(n==0&&m==0) Break; the for(intI=1; i<=m;i++) scanf ("%d%d%d",&t[i].x,&t[i].y,&t[i].c); *Sort (t+1, t+1+m,cmp); $ intCnt=0, ans=INF;Panax Notoginseng for(intI=1; i<=m;i++) - { the intCnt=0; + for(intj=1; j<=n;j++) fa[j]=J; A for(intj=i;j<=m;j++) the { + if(FFA (t[j].x)! =FFA (T[J].Y)) - { $Fa[ffa (t[j].x)]=FFA (T[J].Y); $cnt++; - } - if(cnt==n-1) {ans=mymin (ANS,T[J].C-T[I].C); Break;} the } - }Wuyi if(Ans==inf) printf ("-1\n"); the Elseprintf"%d\n", ans); - } Wu return 0; -}
View Code
Not the same as LA3887, La poisonous, Mad wa. Blue Book's Chen Feng Code is also WA's AH smg!!
2016-11-01 21:24:53
"UVA 1395" Slim Span (Slim tree)