1504. Best Mean Route

A delivery company has n depots numbered 0 to n - 1 and one-way tunnels between them. Each entry of edges is [u, v, w]: a tunnel from depot u to depot v with profit w, which may be negative. The tunnel network never contains a cycle, and tunnels between the same pair of depots may repeat.

A route is a path that starts at source, ends at target and uses at least one tunnel. Its quality is the average profit of the tunnels it uses. Return the largest quality over all routes. Some route is guaranteed to exist. Your answer is accepted when it is within 1e-6 absolute or relative error of the true value.

Hint: binary search a candidate average r; it is reachable exactly when the best path total after subtracting r from every tunnel is at least 0, which a DP in topological order finds. Aim for O((n + m) log W) time and O(n + m) space.

Example 1

Input:
n = 4edges = [[0,1,6],[1,3,2],[0,2,3],[2,3,3]]source = 0target = 3
Output:
4
Explanation:

The route 0-1-3 averages (6+2)/2 = 4 and the route 0-2-3 averages 3, so the best is 4.

Example 2

Input:
n = 2edges = [[0,1,-7]]source = 0target = 1
Output:
-7
Explanation:

The only route is the single tunnel with profit -7.

Example 3

Input:
n = 5edges = [[0,1,1],[1,2,9],[2,4,9],[0,4,6]]source = 0target = 4
Output:
6.333333333333333
Explanation:

The long route averages 19/3, about 6.333, which beats the direct tunnel of 6.

Constraints

2 ≤ n ≤ 1000

1 ≤ edges.length ≤ 5000

0 ≤ u, v < n; -104 ≤ w ≤ 104

The graph is acyclic; source ≠ target; at least one path from source to target exists.

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001

Expected complexity

Time
O((n + m) log W)
Space
O(n + m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…