Ride-hailing app~45 min2s · 256 MBtarget O((n + q) log n) time, O(n log n) spacedfs · tree-recursion
A ride-sharing service has n pickup stops joined by n - 1 two-way roads, so that every stop reaches every other stop by exactly one route. Each road has a length in metres.
Three riders at three stops want to share one car. They pick a meeting stop, which may be any stop of the network, and each rider travels there by road. For each group of three riders, the service wants the smallest total distance the three riders can travel.
Write best_meeting_cost(n, roads, groups).
n stops, numbered from 0 to n - 1.roads[i] is [a, b, w]: a two-way road between stops a and b of length w. The roads connect all the stops.groups[j] is [a, b, c]: three riders at stops a, b and c. Two or all three riders may be at the same stop.Input: n = 8, roads = [[0,1,4],[0,2,3],[1,3,2],[1,4,6],[2,5,1],[2,6,5],[5,7,2]], groups = [[3,4,7],[3,4,1],[6,7,5],[0,0,0],[3,6,7],[4,4,6]]
Output: [18, 8, 8, 0, 17, 18]Stop 0 joins stops 1 and 2. Stop 1 joins stops 3 and 4, stop 2 joins stops 5 and 6, and stop 5 joins stop 7. For the group at stops 3, 4 and 7, the best meeting stop is stop 1. The riders travel 2, 6 and 10 metres, which is 18.
On a tree, the three paths between the riders meet at one middle stop. Each road between a rider and the middle stop is used by exactly two of the three pairwise paths. So the smallest total is half of the sum of the three pairwise distances.
The solution measures each distance with the distance of each stop from the root, far, and the lowest common ancestor. The distance between two stops is far[a] + far[b] - 2 × far[lowest common ancestor].
| Pair | Lowest common ancestor | Distance |
|---|---|---|
| 3 and 4 | 1 | 6 + 10 - 2 × 4 = 8 |
| 4 and 7 | 0 | 10 + 6 - 0 = 16 |
| 3 and 7 | 0 | 6 + 6 - 0 = 12 |
The three distances add up to 36, and half of that is 18.
Input: n = 4, roads = [[0,1,5],[1,2,3],[2,3,4]], groups = [[0,3,1],[3,0,0],[1,2,3]]
Output: [12, 12, 7]On a path, the rider in the middle is the meeting stop, and the others travel to it. For the group at stops 0, 3 and 1, the distances 0 to 1 and 1 to 3 add to 5 + 7 = 12.
Input: n = 1, roads = [], groups = [[0,0,0]]
Output: [0]All three riders are already at the only stop.
1 ≤ n ≤ 50,000roads.length = n - 1, each road is [a, b, w] with 0 ≤ a, b < n, a ≠ b and 1 ≤ w ≤ 10^6, and the roads connect all stops1 ≤ groups.length ≤ 50,000, and each group is [a, b, c] with 0 ≤ a, b, c < nSearching the whole tree from each rider costs about 3 × n steps for a group. For 50,000 groups on 50,000 stops that is about 7.5 × 10^9 steps. Preparing the tree once costs about n log n, which is under 10^6, and each group then costs a few table lookups.