Maps app~25 min2s · 256 MBtarget O(n log n + q) time, O(n log n) spacetree-recursion
You work on a maps app for a region of towns. The roads join the towns so that there is exactly one route between any two towns, which makes the road network a tree. Each road has a length in kilometres.
Your team lead asks: "For a list of trips, how long is each one?" A trip goes from one town to another along the only route between them. The region has up to 50,000 towns, and the app must answer up to 50,000 trips at once.
Write trip_lengths(n, roads, trips).
n is the number of towns, numbered 0 to n - 1.roads[i] = [a, b, length] is a road between towns a and b. There are exactly n - 1 roads, and every town can reach every other.trips[j] = [a, b] asks for the length of the route from town a to town b. The two towns can be the same.A trip from a town to itself has length 0.
Input: n = 7, roads = [[0, 1, 4], [0, 2, 6], [1, 3, 3], [1, 4, 5], [2, 5, 2], [2, 6, 7]], trips = [[3, 4], [3, 5], [6, 6], [4, 0]]
Output: [8, 15, 0, 9]| Trip | Route | Length |
|---|---|---|
| 3 to 4 | 3, 1, 4 | 3 + 5 = 8 |
| 3 to 5 | 3, 1, 0, 2, 5 | 3 + 4 + 6 + 2 = 15 |
| 6 to 6 | the town itself | 0 |
| 4 to 0 | 4, 1, 0 | 5 + 4 = 9 |
Input: n = 1, roads = [], trips = [[0, 0]]
Output: [0]Input: n = 4, roads = [[0, 1, 10], [1, 2, 10], [2, 3, 10]], trips = [[0, 3], [3, 1], [2, 2]]
Output: [30, 20, 0]1 ≤ n ≤ 50,000len(roads) = n - 1, and the roads form one tree.1 ≤ length ≤ 50,0001 ≤ len(trips) ≤ 50,000Walking each trip one road at a time can take up to 49,999 steps, and a chain of towns with random trips averages about 16,700 steps. For 50,000 trips that is about 800 million steps. The longest route can be 49,999 roads of 50,000 km, which is 2,499,950,000 km. A method that answers each trip in a few steps after one preparation of about 1,600,000 table entries fits easily.