Online store~40 min2s · 256 MBtarget O(n^3 + 2^k x k^2) time, O(2^k x k + n^2) spaceshortest-paths · dp
A warehouse has numbered locations joined by two-way aisles, and each aisle has a walking cost. A picker enters at location 0 and must visit every location on a pick list, in any order. The picker may pass through any location, including pick locations, as often as needed.
The picker does not have to return to the entrance. You want the cheapest total walking cost to visit every pick location.
Write cheapest_pick_walk(n, aisles, picks).
n locations, numbered from 0 to n - 1. The picker starts at location 0.aisles[i] is [a, b, cost]: a two-way aisle between different locations. Two aisles may join the same pair, and the cost may be 0.picks lists the distinct locations to visit, in any order. It may include location 0, and it may be empty.Input: n = 6, aisles = [[0,1,5],[0,2,6],[0,3,6],[1,5,1],[2,3,3],[2,4,5],[3,4,3],[3,5,4]], picks = [5, 3, 4]
Output: 13The cheapest walk is 0, 1, 5, 3, 4. It costs 5 + 1 + 4 + 3 = 13, and it visits the picks in the order 5, 3, 4. Going first to the nearest pick, location 3, costs 16 in all.
The solution first finds the cheapest walk between every two locations. Then it works over subsets of the picks. The table shows the cheapest walk that visits the picks in each subset and ends at the pick named in the column.
| Locations visited | Ends at 5 | Ends at 3 | Ends at 4 |
|---|---|---|---|
| 5 | 6 | - | - |
| 3 | - | 6 | - |
| 5, 3 | 10 | 10 | - |
| 4 | - | - | 9 |
| 5, 4 | 16 | - | 13 |
| 3, 4 | - | 12 | 9 |
| 5, 3, 4 | 16 | 16 | 13 |
The last row holds the walks that visit all three picks, and its smallest value is 13.
Input: n = 3, aisles = [[0,1,3]], picks = [1, 2]
Output: -1Location 2 has no aisle, so the picker cannot reach it.
Input: n = 4, aisles = [[0,1,2],[1,2,2],[2,3,2]], picks = [3, 1]
Output: 6Location 1 lies on the way to location 3. The walk 0, 1, 2, 3 visits both for 6.
1 ≤ n ≤ 600 ≤ aisles.length ≤ 400, and each aisle is [a, b, cost] with 0 ≤ a, b < n, a ≠ b and 0 ≤ cost ≤ 10,0000 ≤ picks.length ≤ 12, and the picks are distinct locations from 0 to n - 1Trying every order of 12 picks means 12! = 479,001,600 orders, each costing 12 steps, about 5.7 × 10^9 steps. Working over subsets costs 2^12 × 12 × 12 = 589,824 steps, and the table of walks between locations costs 60^3 = 216,000 steps.