This question evaluates understanding of tree data structures and ancestor-walk queries, assessing competency in traversing rooted trees, interpreting parent arrays, and designing efficient query-processing methods for large n and q.
You are given a rooted tree with n nodes labeled 1..n, represented by a parent array par[1..n]:
par[i]
is the parent of node
i
par[root] = -1
Example:
par = [-1, 1, 1, 2, 2, 2, 2]
(meaning
par[1] = -1
,
par[2] = 1
, …)
You will be given q queries. Each query provides:
u
k ≥ 0
(“number of commands/steps”)
For each query, start at node u and move to the parent exactly k times (or until you reach the root). If you reach the root before using all steps, you remain at the root.
For each query, output the label of the final node where you stop.
Design an approach efficient for large n, q (e.g., up to 2e5).