problems / 203

Constant-Time Range Minimum Query

medium sparse-table arrays 800 ms · 256 MB

Constant-Time Range Minimum Query

You are given an array of integers. Your task is to answer multiple range minimum queries efficiently.

Input

The first line contains n (1 ≤ n ≤ 100,000), the size of the array.

The second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the array elements.

The third line contains q (1 ≤ q ≤ 100,000), the number of queries.

The next q lines each contain two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n), asking for the minimum value in the range [l_i, r_i] (1-indexed, inclusive on both ends).

Output

For each query, print the minimum value in the specified range.

Notes

The solution must preprocess the array in O(n log n) time and answer each query in O(1) time.

Example 1

Input

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

Output

1
1
1

Example 2

Input

4
10 2 8 3
4
1 1
1 2
1 4
3 4

Output

10
2
2
3

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

Hint 1

With n and q both up to 10^5, scanning the range for each query is too slow. What could you precompute once so that many queries are fast?

Hint 2

Precompute the minimum of every window whose length is a power of two, for every starting index. Can a range of arbitrary length be covered by windows of a single power-of-two length?

Hint 3

Two windows of the same length may overlap, and that is harmless for a minimum. For a query, choose the largest power-of-two length that fits in the range, and take one window at each end of [l, r].

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

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