Maps app~40 min4s · 256 MBtarget O((n + q) log n) time, O(n log n) spacedfs
You work on a maps app. A region has road junctions numbered from 0, joined by roads so that exactly one route links any two junctions. Junction 0 is the main junction, and every other junction hangs below it.
Three friends start at three junctions and want to meet where their total walking is smallest. Your team lead asks: "Which junction should each group meet at?" The region has up to 100,001 junctions, and there are up to 40,000 groups.
Write meeting_junctions(parents, trips).
parents[i] is the parent of junction i + 1, so there are len(parents) + 1 junctions. Every parent has a smaller number than its child, and junction 0 has no parent.trips[k] = [a, b, c] gives the starting junctions of one group. They may repeat.a, b and c. On a tree this junction is always unique.Input: parents = [0, 0, 1, 1, 2, 2, 5], trips = [[3, 4, 5], [3, 4, 6], [7, 6, 5], [0, 3, 7], [4, 4, 4]]
Output: [1, 1, 5, 0, 4]The roads are 1 and 2 below 0, then 3 and 4 below 1, 5 and 6 below 2, and 7 below 5.
| Group | Meeting junction | Why |
|---|---|---|
[3, 4, 5] |
1 | 3 and 4 join at 1, and 5 reaches 1 through 2 and 0, so walking to 1 costs 1 + 1 + 3 = 5 |
[3, 4, 6] |
1 | 3 and 4 are both next to 1 |
[7, 6, 5] |
5 | 6 and 5 are in the branch of 2, and 7 is just below 5 |
[0, 3, 7] |
0 | The groups lie in different branches, so the root is on every route |
[4, 4, 4] |
4 | All three are at the same junction |
Input: parents = [0], trips = [[0, 1, 1], [1, 1, 0]]
Output: [1, 1]Two junctions joined by one road. Two friends stand at junction 1, so the third walks to them.
Input: parents = [0, 1, 1], trips = [[2, 2, 2], [3, 3, 3]]
Output: [2, 3]When all three are at the same junction, they meet there.
1 ≤ len(parents) ≤ 100,000, and 0 ≤ parents[i] ≤ i.1 ≤ len(trips) ≤ 40,0000 ≤ a, b, c ≤ len(parents).Walking up a road to find a common ancestor costs up to 100,000 steps, and a group needs three of them. That is 12 billion steps for 40,000 groups. You need about log n steps for each common ancestor, which is about 17, by jumping up the tree in powers of two.