A toll-road network connects n towns, numbered 0 to n - 1, with m two-way roads.
Road i connects towns u and v and charges a toll of w to use. A driver cares about the single
WORST (highest) toll paid on their route, since that is the most they will ever be charged at one
booth.
Given a starting town s and a destination town t (with s != t), print the smallest possible value
of the worst toll along any route from s to t (i.e., choose the route that minimizes its own
maximum toll). If t is unreachable from s, print -1 instead.
Line 1: two integers n m.
Next m lines: three integers u v w -- an undirected road between towns u and v with toll w
(towns are 0-indexed).
Last line: two integers s t.
A single integer: the minimum possible value of the worst toll along a route from s to t, or -1
if unreachable.
Example 1
Input
4 4 0 1 10 1 3 2 0 2 3 2 3 4 0 3
Expected
4
Explanation
Route 0 -> 2 -> 3 has a worst single toll of 4 (max(3,4)), better than 0 -> 1 -> 3 whose worst toll is 10, so the smallest possible worst-toll is 4.
Example 2
Input
3 1 0 1 6 0 2
Expected
-1
Explanation
Town 2 is not linked to town 0 by any road, so no route exists and the answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →