A project has n tasks numbered 0 to n - 1, numbered in an order consistent with their
dependencies: every prerequisite link only ever points from a lower-numbered task to a higher-numbered
task, so the task graph never contains a cycle. There are m such links; a link from task u to task
v with weight w means that once task u is finished, task v can be finished w minutes later
(assuming v's other prerequisites, if any, are also satisfied at least that early). Task 0 is
always the project's starting task and is finished at time 0.
Print the earliest possible time a given target task can be finished, taking the fastest chain of
dependencies into account. If the target task can never be finished (it is not reachable from task
0), print -1 instead.
Line 1: two integers n m.
Next m lines: three integers u v w, with u < v always -- task v can finish w minutes after
task u finishes (tasks are 0-indexed).
Last line: one integer, the index of the target task.
A single integer: the earliest completion time of the target task, or -1 if it is unreachable.
Example 1
Input
4 4 0 1 2 0 2 5 1 2 1 2 3 2 3
Expected
5
Explanation
Task 2 is fastest reached via 0 -> 1 -> 2 costing 2+1=3 minutes (cheaper than the direct 0 -> 2 link costing 5); adding the final 2 -> 3 step (2 minutes) gives a total of 5.
Example 2
Input
3 1 0 1 4 2
Expected
-1
Explanation
Task 2 has no incoming link at all, so it can never be started, 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 →