Minimum Cost Paths#11205

Minimum Cost Paths

1 second
128 megabytes
Very hard

Farmer John's pasture can be regarded as an n \times m 2D grid of square cells (like a large chessboard). The cell at the -th row from the top and -th column from the left is denoted by for each x \in [1, n], y \in [1, m]. Furthermore, for each y \in [1, m], the -th column is associated with the cost c_y (1 \le c_y \le 10^9).

Bessie starts at cell . If she is currently located at cell , she may perform one of the following moves:

You are given independent queries, each of the form (x_i, y_i) (x_i \in [1, n], y_i \in [1, m]). For each query, compute the minimum possible total cost for Bessie to move from to (x_i, y_i).

\InputFileThe first line contains two integers and (2 \le n \le 10^9, 2 \le m \le 2 \times 10^5).

The second line contains integers c_1, c_2, \ldots, c_m (1 \le c_y \le 10^9).

The third line contains (1 \le q \le 2 \times 10^5).

Each of the next lines contains two integers x_i and y_i (x_i \in [1, n], y_i \in [1, m]).

\OutputFilePrint lines. For each query, output a single line containing the answer.

Note: The large size of integers involved may require the use of 64-bit integer types (e.g., long long in C/C++).

\ExamplesThe output in a grid format:

    1  2  3  4
  *--*--*--*--*
1 | 0| 1| 2| 3|
  *--*--*--*--*
2 | 1| 5| 9|13|
  *--*--*--*--*
3 | 2|11|20|29|
  *--*--*--*--*
4 | 3|19|35|49|
  *--*--*--*--*
5 | 4|29|54|69|
  *--*--*--*--*

Examples

Example 1

Loading
Loading