A project plan has n tasks numbered 0 to n - 1, numbered so that every dependency
link points from a lower-numbered task to a higher-numbered task (the plan never contains a cycle).
There are m links; link i goes from task u to task v and means task v can only begin w
units of time after task u finishes (this is the duration attributed to that step of the plan). Task
0 is the project's start, beginning at time 0.
The project's critical path to a given target task is the LONGEST possible total duration among all
chains of dependencies from task 0 to that target (this is the earliest time by which every
prerequisite chain reaching the target is guaranteed to be finished). Print the length of the critical
path to the given target task. If the target task is not reachable from task 0 at all, print -1
instead.
Line 1: two integers n m.
Next m lines: three integers u v w, with u < v always -- task v can begin w units after task
u finishes (tasks are 0-indexed).
Last line: one integer, the index of the target task.
A single integer: the length of the critical (longest) path from task 0 to the target task, or -1
if it is unreachable.
Example 1
Input
4 4 0 1 3 0 2 1 1 3 2 2 3 5 3
Expected
6
Explanation
The chain 0 -> 2 -> 3 takes 1+5=6 time units, longer than 0 -> 1 -> 3 which takes 3+2=5, so the critical (longest) path to task 3 takes 6 units.
Example 2
Input
3 1 0 1 4 2
Expected
-1
Explanation
No link ever leads into task 2, so it is unreachable from task 0, giving -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 →