Slim Span
InterviewTime limit2sMemory limit128 MB
Given a weighted graph, find the spanning tree that minimizes the difference between its largest and smallest edge weight, or report -1 if disconnected.
- Level
Medium4 of 10
- Topics
- Union-find, Sorting, Greedy
- Solved
- No attempts yet
Problem
Given an undirected weighted graph , you must find one of its spanning trees as specified below.
The graph is an ordered pair , where is a set of vertices and is a set of undirected edges . Each edge has a weight .
A spanning tree is a tree (a connected subgraph without cycles) that connects all vertices with edges. The slimness of a spanning tree is defined as the difference between the largest weight and the smallest weight among the edges of .
Figure 5: A graph and the weights of the edges.
For example, a graph in Figure 5(a) has four vertices and five undirected edges . The weights of the edges are , , , , , as shown in Figure 5(b).
Figure 6: Examples of the spanning trees of .
There are several spanning trees for . Four of them are depicted in Figure 6(a)-(d). The spanning tree in Figure 6(a) has three edges whose weights are , , and ; the largest weight is and the smallest is , so the slimness of is . The slimnesses of the spanning trees , , and shown in Figure 6(b), (c), and (d) are , , and , respectively. You can easily see that the slimness of any other spanning tree is at least , so the spanning tree in Figure 6(d) is one of the slimmest spanning trees, with slimness .
Your job is to write a program that computes the smallest slimness.
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, and items on a line are separated by a space.
is the number of vertices and the number of edges. You may assume and . Each and () is a positive integer at most , representing the two vertices and connected by the -th edge . Each is a positive integer at most , the weight of . You may assume the graph is simple: it has no self-loops (edges connecting a vertex to itself) and no parallel edges (two or more edges whose endpoints are the same pair of vertices).
Output
For each dataset, if the graph has spanning trees, print the smallest slimness among them. Otherwise, print . The output must not contain extra characters.