Function and Queries

Given an array and a recurrence f(i,j)=min(f(i-1,j),f(i-1,j-1))+a_j, answer up to 1e5 offline queries for f(x,y).

Hard9Dynamic programmingDivide and conquerMathCombinatoricsNo attempts yetTime limit2sMemory limit512 MB

Problem

You are given an array a=(a1,a2,,an)a = (a_1, a_2, \dots, a_n) of length nn. The function ff is defined as follows.

f(1,j)=aj(1jn)f(1,\, j) = a_j \qquad (1 \le j \le n)

f(i,j)=min(f(i1,j), f(i1,j1))+aj(2in, ijn)f(i,\, j) = \min(f(i-1,\, j),\ f(i-1,\, j-1)) + a_j \qquad (2 \le i \le n,\ i \le j \le n)

You are also given mm queries. Each query consists of two integers xix_i and yiy_i, and asks for the value of f(xi,yi)f(x_i, y_i). Write a program that answers every query.

Input

The first line contains the size nn of the array aa (1n1051 \le n \le 10^5).

The second line contains a1,a2,,ana_1, a_2, \dots, a_n separated by spaces. (0aj1040 \le a_j \le 10^4)

The third line contains the number of queries mm (1m1051 \le m \le 10^5). Each of the next mm lines contains one query as xix_i and yiy_i. (1xiyin1 \le x_i \le y_i \le n)

Output

Print the value of f(xi,yi)f(x_i, y_i) for each query, one per line, in the order the queries are given.