A network has n nodes labelled 1..n connected by m one-way links. A link u v w means a signal takes w time units to travel from u to v. A signal is emitted from a source node s and travels along links, always by the fastest route.
Report the time at which the last node receives the signal, i.e. the maximum over all nodes of the shortest travel time from s. If any node can never receive the signal, report -1.
Line 1: two integers n and m.
The next m lines each contain three integers u v w, a directed link from u to v with travel time w.
The final line contains one integer s, the source node.
A single integer: the time for the signal to reach every node, or -1 if some node is unreachable.
Example 1
Input
4 4 1 2 1 1 3 4 2 3 1 3 4 1 1
Expected
3
Explanation
Shortest times from node 1 are: node 1 = 0, node 2 = 1, node 3 = 2 (via 2), node 4 = 3. The last node receives the signal at time 3.
Example 2
Input
3 1 1 2 5 1
Expected
-1
Explanation
From node 1 you reach node 2 in 5, but node 3 has no incoming link and is unreachable, so 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 →