



The first line contains an integer ‘T’ which denotes the number of test cases.
For each test case:
The first line contains a single integer ‘N’, denoting the number of nodes.
Each of the following ‘N’ - 1 line contains two space-separated integers, ‘ui’ and ‘vi’, which means an edge connects these two nodes.
The following line will contain a single integer ‘Q’, denoting the number of queries you have to answer for the given tree.
In the following ‘Q’ lines, each one will have two numbers, ‘u’ and ‘v’, for which you have to find the LCA of ‘u’ and ‘v’.
Your task is to print ‘Q’ lines for each test case.
The ‘Q’ lines should be the LCA of the given ‘u’ and ‘v’, respectively.
1<= ‘T' <= 5
1 <= ‘N’ <= 10^5
1 <= ‘Q’ <= 10^5.
1 <= ‘u’, ‘v’ <= ‘N’.
Time Limit: 1 sec
We will store the depth and the direct parent of each node using a dfs.
Now, if we have to find the LCA to two nodes, first we would move upward the node which has a higher depth until both the nodes reach the same depth, then we will move both the node upward until they become the same, the node that we reach will be the LCA.
Approach:
Using Sparse Table, we can efficiently find the kth ancestor of any node in the tree in O(log(N)). Using this, we can divide the problem of finding the LCA into two parts. We use two pointers that initially point to the two nodes whose LCA we have to find.
Let’s take an example:
We have to find the LCA of nodes ‘4’ and ‘5’.
The black circle around the nodes denote the current positions of both the pointers.
Initially, both point to initial nodes which are node ‘4’ and node ‘5’.
Now, one of the pointers moves upwards so that both pointers point to nodes at the same level. I.e. we will move our pointer upward, which has a higher depth until both of the pointers reach the same depth. This can be done in O(log(N)) by using a sparse table.
After this, we determine the minimum number of steps needed to move both pointers upwards to point to the same node. The node to which the pointers point after this is the lowest common ancestor.
The example suffices to move both pointers one step upwards to node 1, which is the lowest common ancestor.
Initialize a variable ‘level’ to log(N) + 3;
Initialize a 2d array ‘dp’ of dimension ‘(N + 1) * level’ to find the ‘kth’ ancestor of any tree node using the sparse table technique.
Initialize an array ‘depth’ of length ‘N + 1’ to store the depth of all the nodes from root node 1.
Func Main():