Ad platform~45 min2s · 256 MBtarget O((n + q) log n) time, O(n log n) spacetree-recursion · dfs
An ad platform keeps its accounts in a tree. Account 0 is the top, and parents[v] is the account that manages account v. The ids carry no order: a manager may have a larger id than the accounts it manages.
An account counts as managing itself. For a range of ids from l to r, the team wants the lowest account that manages every account in the range. There are many such ranges, so each answer must be quick.
Write shared_owner(parents, queries).
parents.length accounts, numbered from 0. parents[0] is -1, and every other entry is the id of the manager of that account.queries[i] is [l, r] with l ≤ r: a range of ids, both ends included.l to r.Input: parents = [-1, 0, 0, 1, 1, 2, 2, 3, 5, 5], queries = [[3,4],[7,8],[4,7],[0,9],[8,9],[6,6],[5,6]]
Output: [1, 0, 0, 0, 5, 6, 2]Accounts 1 and 2 report to 0. Accounts 3 and 4 report to 1, accounts 5 and 6 report to 2, account 7 reports to 3, and accounts 8 and 9 report to 5.
The solution walks the tree and writes an account into a tour every time the walk arrives at it or comes back to it. For this tree the tour has 19 entries: 0, 1, 3, 7, 3, 1, 4, 1, 0, 2, 5, 8, 5, 9, 5, 2, 6, 2, 0. Between two accounts' first visits, the shallowest account on the tour is their lowest common manager.
For a range of ids, the lowest manager of the whole range is the lowest manager of the two accounts that the walk first reaches earliest and latest. Take the query [4, 7].
| Step | Value |
|---|---|
| First visits of accounts 4, 5, 6, 7 | 6, 10, 16, 3 |
| Earliest and latest first visit | 3 (account 7) and 16 (account 6) |
| Tour entries from position 3 to 16 | 7, 3, 1, 4, 1, 0, 2, 5, 8, 5, 9, 5, 2, 6 |
| Shallowest account in that stretch | 0 |
So the answer to [4, 7] is 0.
Input: parents = [-1], queries = [[0,0]]
Output: [0]One account manages itself.
Input: parents = [-1, 0, 1], queries = [[1,2],[0,2],[2,2]]
Output: [1, 0, 2]On a chain, the lowest manager of a range is the shallowest account in it.
1 ≤ parents.length ≤ 60,000, parents[0] = -1, and every other entry is a valid account that makes the accounts a tree rooted at 01 ≤ queries.length ≤ 60,000, and each query is [l, r] with 0 ≤ l ≤ r < parents.lengthClimbing from each account of a range costs up to n × n steps for one query on a deep tree. With 60,000 accounts and 60,000 ranges that is more than 10^14. A tour and three tables answer each query in a few steps after about 3 × 10^6 steps of preparation.