Test instructions: In the minimum spanning tree, the largest edge minus the minimum edge minimum value.
It's easy to see the =_=.
Sort each edge from small to large and then enumerate the smallest spanning tree from smallest to largest, updating the minimum when forming a spanning tree
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <algorithm>5 using namespacestd;6 Const intINF =0x3f3f3f3f;7 Const intMax = the;8 Const intN = the;9 intFather[n];Ten structEdge One { A intx, Y, Dist; - }; - Edge Edge[max]; the intcmp (Edge t1, Edge T2) - { - returnT1.dist <t2.dist; - } + intFind_father (intx) - { + if(x = =Father[x]) A returnx; at returnFATHER[X] =Find_father (father[x]); - } - intMain () - { - intN, M; - while(SCANF ("%d%d", &n, &m)! =EOF) in { - if(M = =0&& n = =0) to Break; + for(inti =0; I < m; i++) - { thescanf"%d%d%d", &edge[i].x, &EDGE[I].Y, &edge[i].dist); * } $Sort (edge, Edge +m, CMP);Panax Notoginseng intMinn =INF; - for(inti =0; I < m; i++) the { + for(intj =0; J <= N; J + +) AFATHER[J] =J; the intCNT =0; + for(intj = i; J < M; J + +)//enumerate each spanning tree in turn - { $ intFX =Find_father (edge[j].x); $ intFY =Find_father (EDGE[J].Y); - if(FX! =fy) - { theFATHER[FX] =fy; -cnt++;Wuyi if(cnt = = N-1)//Once the spanning tree is formed, j is the maximum edge, I is the least weight, and the subtraction is updated the { -Minn = MIN (minn, edge[j].dist-edge[i].dist); Wu Break; - } About } $ } - } - if(Minn = =INF) -printf"-1\n"); A Else +printf"%d\n", Minn); the } - return 0; $}View Code
Uva1395slim Span (enumeration minimum spanning tree)