Lowest Common Ancestor 2
InterviewTime limit1.5sMemory limit256 MB
Given a rooted tree with up to 100,000 nodes, answer up to 100,000 lowest common ancestor queries.
Problem
A tree with vertices is given (). The vertices are numbered 1 to , and vertex 1 is the root.
You are given pairs of nodes (). For each pair, print the number of the lowest common ancestor of the two nodes. Among all common ancestors of the two nodes, the lowest common ancestor is the one farthest from the root.
A vertex is an ancestor of itself. So if one vertex of a pair is an ancestor of the other, the answer is that ancestor.
Input
The first line contains the number of nodes . Each of the next lines contains the numbers of two vertices that are connected in the tree. The two vertices on a line are not necessarily written in parent, child order.
The next line contains the number of pairs , and each of the following lines contains one pair of vertices whose lowest common ancestor you must find.
Output
Print lines. On each line print the number of the lowest common ancestor of the corresponding pair, in the order the pairs are given.