Meeting Point in the Insertion Tree
A binary search tree starts empty. You are given a permutation p_1, p_2, ..., p_n of 1..n, and
its keys are inserted into the tree one at a time, in this order, using the usual rule: starting at
the root, repeatedly step to the left child if the key being inserted is smaller than the current
node's key, or to the right child if it is larger, until falling off the tree; the key is then
attached there as a new leaf. The tree is never rebalanced, so after all n insertions it can be as
unbalanced as a single chain.
Once every key has been inserted, you must answer q queries. Each query names two distinct keys
u and v (both were inserted, since every value from 1 to n occurs exactly once in the
permutation). Report the key stored at their lowest common ancestor — the deepest node that is an
ancestor of both u and v, where a node counts as an ancestor of itself.
Input
The first line contains n (2 ≤ n ≤ 2·10^5).
The second line contains n distinct integers p_1, ..., p_n (1 ≤ p_i ≤ n) — a permutation of
1..n, the order in which keys are inserted into the initially empty tree.
The third line contains q (1 ≤ q ≤ 2·10^5).
Each of the next q lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — a query.
Output
Print q lines. For each query, print the key stored at the lowest common ancestor of u and v.
Notes
In the first example the keys are inserted in the order 4, 2, 6, 1, 3, 5, 7, giving the tree
4
/ \
2 6
/ \ / \
1 3 5 7
The query 1 3 asks for the lowest common ancestor of the leaves 1 and 3, which is 2. The
query 1 7 asks for the lowest common ancestor of 1 and 7, which is the root 4.