Lowest Common Ancestor
InterviewTime limit3sMemory limit256 MB
Given a rooted tree, answer each query with the number of the deepest vertex that is an ancestor of both given vertices.
Problem
You are given a tree with vertices. The vertices are numbered from 1 to , and vertex 1 is the root.
The lowest common ancestor of two vertices and is the vertex that is an ancestor of both and lies farthest from the root. A vertex counts as an ancestor of itself here.
You are given pairs of vertices. For each pair, find the number of its lowest common ancestor.
Input
The first line contains the number of vertices ().
Each of the next lines contains the numbers of two vertices joined by an edge. An edge is not guaranteed to be given in parent then child order.
The next line contains the number of queries (). Each of the following lines contains one pair of vertices. The two vertices in a pair may be the same.
Output
Print lines. On the -th line print the number of the lowest common ancestor of the -th pair given in the input.