Relay critical paths
MediumOnline Assessment
Find the longest route through a relay course and count how many routes achieve it.
A relay course has n checkpoints numbered 0 to n - 1, joined by one-way legs. Each leg [a, b, length] lets a runner go from checkpoint a to checkpoint b and measures length. The legs never form a loop, but the checkpoint numbers say nothing about their order along the course, and two checkpoints may be joined by several different legs.
A route starts at an entry checkpoint (one with no leg leading into it), follows legs one after another, and ends at an exit checkpoint (one with no leg leading out of it). A checkpoint with no legs at all is both an entry and an exit, so it is a route of length 0 by itself. The length of a route is the sum of its legs' lengths.
Two routes are different if they use different legs in any position, so two parallel legs between the same checkpoints give two different routes. Routes of the same length that finish at different exits are all counted.
Input: n, the number of checkpoints, and legs, a list of [a, b, length] triples.
Output: a list [longest, count]: the length of the longest route, and the number of routes with exactly that length, modulo 1_000_000_007. If n is 0 there are no routes: return [0, 0].
The number of routes can grow exponentially with the number of checkpoints, so listing the routes one by one will be too slow.
Example 1
- Input:
- [5,[[3,1,4],[3,4,4],[1,0,2],[4,0,2],[0,2,5]]]
- Output:
- [11,2]
- Explanation
- Checkpoint 3 is the only entry (nothing leads into it) and checkpoint 2 is the only exit. The two routes 3 -> 1 -> 0 -> 2 and 3 -> 4 -> 0 -> 2 both measure 4 + 2 + 5 = 11, the longest there is, so the answer is [11, 2]. Checkpoint numbers say nothing about the order of the legs.
Example 2
- Input:
- [4,[[0,1,5],[0,1,5],[0,2,5],[3,2,1]]]
- Output:
- [5,3]
- Explanation
- Entries are 0 and 3, exits are 1 and 2. The two parallel legs 0 -> 1 are different routes, each of length 5, and 0 -> 2 is also 5. The route 3 -> 2 is only 1. Three routes tie for the longest, so the answer is [5, 3]. Ties are counted across every exit.
Example 3
- Input:
- [4,[[2,0,0],[0,1,0]]]
- Output:
- [0,2]
- Explanation
- Checkpoint 3 has no legs at all, so it is both an entry and an exit: a route of length 0 by itself. The other route is 2 -> 0 -> 1 whose zero-length legs also total 0. Both routes are longest, so the answer is [0, 2].
Constraints
0 <= n <= 3,0000 <= legs.length <= 6,000- each leg is
[a, b, length]with0 <= a, b < n,a != band0 <= length <= 1,000 - the legs never form a cycle; several legs may join the same pair of checkpoints