You are given a directed weighted graph with n nodes labeled from 0 to n - 1. The graph is a list of edges where each edge is [u, v, w0, delta]: a directed edge from node u to node v with initial weight w0. At time step t (starting from t = 0), the weight of this edge is w0 + delta * t.
You start at node 0 at time t = 0. Traversing an edge takes exactly 1 time step. The cost you pay for an edge is its weight at the time step when you begin traversing it.
Return the minimum total cost to travel from node 0 to node n - 1. If node n - 1 cannot be reached, return -1.
Function Signature
def shortest_path_dynamic(n: int, edges: list[list[int]]) -> int:
Rules
-
edges[i] = [u, v, w0, delta]
is a directed edge. It can only be followed from
u
to
v
.
-
You cannot wait at a node. The time at which you start an edge equals the number of edges you have already traversed.
-
An edge started at time
t
costs
w0 + delta * t
. If that value is negative, the edge cannot be used at time
t
.
-
You may visit nodes and reuse edges any number of times. The cost of a walk is the sum of its edge costs, and the answer is the minimum cost over all walks that start at node
0
at time
0
and end at node
n - 1
.
Constraints
-
2 <= n <= 200
-
0 <= edges.length <= n * (n - 1)
-
edges[i].length == 4
-
0 <= u, v < n
-
u != v
-
1 <= w0 <= 1000
-
-10 <= delta <= 10
-
No two edges share the same
(u, v)
pair.
Examples
Input: n = 4, edges = [[0,1,5,-1],[0,2,10,0],[1,3,3,2],[2,3,1,0]]
Output: 10
The walk 0 -> 1 -> 3 starts edge 0 -> 1 at time 0 (cost 5 + (-1) * 0 = 5) and edge 1 -> 3 at time 1 (cost 3 + 2 * 1 = 5), for a total of 10. The walk 0 -> 2 -> 3 costs 10 + 1 = 11, and the graph has no cycles, so no other walk exists.
Input: n = 3, edges = [[0,1,2,0],[1,2,3,0]]
Output: 5
All deltas are 0, so the weights never change and the only walk 0 -> 1 -> 2 costs 2 + 3 = 5.
Input: n = 3, edges = [[0,1,1,0],[1,0,1,0],[0,2,10,-2]]
Output: 6
You are at node 0 only at even times, so edge 0 -> 2 costs 10, 6 or 2 when started at time 0, 2 or 4, and from time 6 on it is unusable because 10 - 12 is negative. The walk 0 -> 1 -> 0 -> 1 -> 0 -> 2 pays 4 for two trips around the cycle plus 2 for the last edge, for a total of 6, which beats 10 (no trip) and 1 + 1 + 6 = 8 (one trip).