A shipping network has n distribution hubs, numbered 0 to n - 1, and m one-way
cargo legs. Leg i moves cargo from hub u to hub v for a total handling-and-transport fee of w.
Multiple legs between the same pair of hubs may exist, at different fees.
Given a source hub s, a destination hub t (with s != t), and a maximum number of legs k that a
shipment is allowed to use, print the minimum total fee to move cargo from s to t using AT MOST k
legs. If no such route exists within the leg budget, print -1 instead.
Line 1: two integers n m.
Next m lines: three integers u v w -- a directed cargo leg from hub u to hub v costing w
(hubs are 0-indexed).
Last line: three integers s t k.
A single integer: the minimum total fee from s to t using at most k legs, or -1 if impossible.
Example 1
Input
4 4 0 1 5 1 2 5 0 2 20 2 3 1 0 3 3
Expected
11
Explanation
Using 3 legs, the route 0 -> 1 -> 2 -> 3 costs 5+5+1=11, cheaper than the 2-leg route 0 -> 2 -> 3 which costs 20+1=21, and 3 legs are allowed, so the answer is 11.
Example 2
Input
4 4 0 1 5 1 2 5 0 2 20 2 3 1 0 3 2
Expected
21
Explanation
With only 2 legs allowed, the cheaper 3-leg route 0 -> 1 -> 2 -> 3 is not permitted, leaving only 0 -> 2 -> 3 at a cost of 20+1=21.
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 →