Ride-hailing app~45 min2s · 256 MBtarget O(2^n x n^2) time, O(2^n x n) spacedp
A same-day delivery courier starts at the depot, visits every stop on the route, and comes back. The map is small: at most 12 stops besides the depot. Travel times are known between every pair of places.
Some stops depend on others. A drop-off cannot happen before its pickup, so a stop may carry a rule that another stop must be visited earlier. The courier wants the shortest round trip that respects every rule.
Write shortest_tour(dist, before).
0 is the depot. Places 1 to n - 1 are the stops, where n is the number of rows of dist.dist[a][b] is the travel time from place a to place b. It need not equal dist[b][a].before[s] is the stop that must be visited before stop s, or -1 when there is no rule. A rule that names the depot is always met. before[0] is -1.-1 when no order respects the rules. With no stops, the tour costs 0.Input: dist = [[0, 4, 7, 5, 9], [4, 0, 3, 6, 8], [7, 3, 0, 5, 4], [5, 6, 5, 0, 2], [9, 8, 4, 2, 0]], before = [-1, -1, 1, -1, 3]
Output: 23Stops 1 to 4 have the rules: stop 2 after stop 1, and stop 4 after stop 3. The trace keeps the shortest trip for each set of visited stops and each last stop.
| Visited stops | Last stop | Shortest trip so far |
|---|---|---|
| 1 | 1 | 4 |
| 1, 2 | 2 | 7 |
| 1, 2, 3 | 3 | 12 |
| 1, 2, 3 | 2 | 14 (order 3, 1, 2) |
| 1, 2, 3, 4 | 4 | 14 (order 1, 2, 3, 4) |
| 1, 2, 3, 4 | 2 | 16 (order 1, 3, 4, 2) |
The best finished trips add the way home. From stop 4 the way home is 9, so 14 + 9 = 23. From stop 2 it is 7, so 16 + 7 = 23. The output is 23.
Input: dist = [[0, 1, 1], [1, 0, 1], [1, 1, 0]], before = [-1, 2, 1]
Output: -1Stop 1 needs stop 2 first, and stop 2 needs stop 1 first, so no order works.
Input: dist = [[0]], before = [-1]
Output: 0The depot alone: the tour costs 0.
1 ≤ dist.length ≤ 13 (the depot and up to 12 stops); dist is a square grid0 ≤ dist[a][b] ≤ 1,000 (travel time)before has the same length as dist, and -1 ≤ before[s] ≤ 12Trying every order of 12 stops means 12!, about 479 million orders, and each order costs 12 steps. That is too slow. But there are only 2^12 = 4,096 sets of stops.
A trip is described by its set and its last stop: about 4,096 × 12 states, each with 12 next steps. That is about 600,000 steps. The small limit is what makes a bitmask possible.