This page is still under construction.

Parts of this page are still being built. What you see may change.

Lowest Common Ancestor

Interview

Time limit3sMemory limit256 MB

Summary
Given a rooted tree, answer each query with the number of the deepest vertex that is an ancestor of both given vertices.
Level

Medium4 of 10

Topics
Tree, DFS
Solved
No attempts yet

Problem

You are given a tree with NN vertices. The vertices are numbered from 1 to NN, and vertex 1 is the root.

The lowest common ancestor of two vertices uu and vv 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 MM pairs of vertices. For each pair, find the number of its lowest common ancestor.

Input

The first line contains the number of vertices NN (2≤N≤500002 \le N \le 50000).

Each of the next N−1N-1 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 MM (1≤M≤100001 \le M \le 10000). Each of the following MM lines contains one pair of vertices. The two vertices in a pair may be the same.

Output

Print MM lines. On the ii-th line print the number of the lowest common ancestor of the ii-th pair given in the input.

Examples1

  1. Example 1

    Input
    15
    1 2
    1 3
    2 4
    3 7
    6 2
    3 8
    4 9
    2 5
    5 11
    7 13
    10 4
    11 15
    12 5
    14 7
    6
    6 11
    10 9
    2 6
    7 6
    8 13
    8 15
    
    Expected output
    2
    4
    2
    1
    3
    1