This page is still under construction.

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

Function and Queries

Time limit2sMemory limit512 MB

Summary
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).
Level

Hard9 of 10

Topics
Dynamic programming, Divide and conquer, Math, Combinatorics
Solved
No attempts yet

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(1≤j≤n)f(1,\, j) = a_j \qquad (1 \le j \le n)

f(i, j)=min⁡(f(i−1, j), f(i−1, j−1))+aj(2≤i≤n, i≤j≤n)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 (1≤n≤1051 \le n \le 10^5).

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

The third line contains the number of queries mm (1≤m≤1051 \le m \le 10^5). Each of the next mm lines contains one query as xix_i and yiy_i. (1≤xi≤yi≤n1 \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.

Examples2

  1. Example 1

    Input
    6
    2 2 3 4 3 4
    4
    4 5
    3 4
    3 4
    2 3
    
    Expected output
    12
    9
    9
    5
    
  2. Example 2

    Input
    7
    1 3 2 3 4 0 2
    4
    4 5
    2 3
    1 4
    4 6
    
    Expected output
    11
    4
    3
    0