Meeting Point in the Insertion Tree

medium binary-search-tree trees segment-tree 1000 ms · 256 MB

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.

Example 1

Input

7
4 2 6 1 3 5 7
4
1 3
1 7
5 7
2 3

Output

2
4
6
2

Example 2

Input

5
1 2 3 4 5
3
1 5
3 5
2 4

Output

1
3
2

Hints · reveal one at a time if you're stuck

Hint 1

The tree can become a long chain, so walking up from the two keys for each query is too slow. Try to work out which key ends up as the common ancestor of two keys from the insertion order alone.

Hint 2

Look at the keys whose values lie between u and v, inclusive. Which of them is inserted first, and why must that key sit above all the others in that range?

Hint 3

Store each key's insertion time in an array indexed by key value. Each query then asks for the position of the minimum over a range of that array, which a sparse table or segment tree can answer quickly.

report an issue Prefer your own editor? sooks prep 86 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.