Problem 440
Kth Ancestor Queries
Hard · 30 pts · Tree, Binary Search, Dynamic Programming, Binary Lifting
Problem
A rooted tree has N nodes labelled 1 to N; you are given each node's parent, with 0 for the root. Answer Q queries: for a node V and a number K, print the K-th ancestor of V (the parent is the 1st ancestor, the grandparent the 2nd, and so on), or -1 if it does not exist. Walking up one step at a time is too slow for deep trees and many queries; binary lifting precomputes each node's 2^j-th ancestor and answers each query in O(log N).
Input
First line: N. Second line: the parents of nodes 1 to N (0 for the root). Third line: Q. Next Q lines: V and K.
Output
Print the answer to each query on its own line.
Constraints
1 <= N, Q <= 100000; 1 <= V <= N; 1 <= K <= N
Example input
7 0 1 1 2 2 3 3 3 4 1 4 2 4 3
Example output
2 1 -1
Explanation
With parents 0 1 1 2 2 3 3 (node 1 is the root), node 4's parent is 2 and its grandparent is 1. So the 1st ancestor of 4 is 2, the 2nd is 1, and a 3rd does not exist (-1).