
Ninja is learning tree data structures. His friend is helping him learn by giving him problems to solve. He gives him a tree with N nodes numbered from 0 to N - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0. Now Ninja has to find the kth ancestor of a given node. The kth ancestor of a tree node is the kth node in the path from that node to the root node.
The first line of input contains a single integer ‘T’, denoting the number of test cases.
The second line of each test case contains a positive integer ‘N’, denoting the number of nodes.
The third line of each test case contains the parent array.
The fourth line of each test case contains a node value and k value.
Output Format :
The first and only line of each test case contains an integer denoting the kth ancestor.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= k <= N <= 5 * 10 ^ 4
0 <= node < N
0 <= parent[i] < N
Time limit: 1 second
2
7
-1 0 0 1 1 2 2
3 1
7
-1 0 0 1 1 2 2
5 2
1
0

In the first test case, it is visible from the figure that the 1st ancestor of a node with the value of 3 is the parent node of 3. Parent of 3 is 1.So we return 1 as our answer.
In the second test case, the first ancestor of the node with the value 5 is 2. Now to find the 2nd ancestor of this node, we find the 1st ancestor of the parent of this node. Now, 1st ancestor of 2 is 0. So we return 0 as our answer
2
7
-1 0 0 1 1 2 2
4 2
7
-1 0 0 1 1 2 2
6 1
0
2
Do some precomputation. Can you use the concept that every number can be represented as the sum of power of 2?
This problem can be solved using a technique known as binary lifting. We need to compute each node, which is exactly 2^i nodes above a given node, and we will store it in an array up[node][i]. Now we will run a DFS to fill this for each node. To compute up[node][i], we can find the node which is 2^i-1 steps above the node which is 2^i - 1 above the current node, hence up[node][i] = up[up[node][i-1]][i-1]. Each query can be answered in log n by treating k as a binary number and moving 2^i steps upward for each set bit in k.
The steps are as follows:
O(Nlog N), where ‘N’ is the number of nodes
The time required to preprocess all the nodes takes O(NlogN) time. So the overall complexity is O(Nlog N) If there were many queries then this approach is very efficient as each query requires O(logN) operation.
O(Nlog N), where ‘N’ is the number of nodes
The space required to preprocess and store all the nodes takes O(NlogN) time. So the overall complexity is O(log N).