Shortest path · Hard
A settlement planner permits at most k directed transfers. Some transfers carry rebates, so costs may be negative.
Return the cheapest source-to-target cost using at most k edges.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ n:integer, edges:[from:integer,to:integer,cost:integer][], source:integer, target:integer, maxEdges:integer }
What each field means
n— number of nodes, with IDs0throughn - 1.edges— directed[from, to, cost]transfers; costs may be negative.source,targetandmaxEdges— start, destination and maximum number of transfers.
Output
Return value and rules
- Return the cheapest total cost of a route using at most
maxEdgestransfers. - Return
nullif no such route reaches the target. - A zero-transfer route is allowed. Repeated nodes are allowed only within the transfer limit.
Constraints
- 1 <= n <= 500; 0 <= edges.length <= 10000; 0 <= maxEdges <= 100
- Costs in [-1000000,1000000]; all endpoints valid. A negative cycle may be traversed only within the edge budget.
Examples
Example 1
{
"edges": [
[
0,
1,
2
],
[
1,
2,
-5
],
[
0,
2,
1
]
],
"maxEdges": 2,
"n": 3,
"source": 0,
"target": 2
}Returns
-3Example 2
{
"edges": [
[
0,
1,
1
]
],
"maxEdges": 0,
"n": 2,
"source": 0,
"target": 1
}Returns
nullRequired complexity
O(km) time and O(n) auxiliary space