#P7294. [USACO21JAN] Minimum Cost Paths P

[USACO21JAN] Minimum Cost Paths P

Description

Farmer John’s pasture can be viewed as a 2D grid made of an N×MN \times M (2N109,2M21052 \le N \le 10^9, 2 \le M \le 2 \cdot 10^5) array of square cells (imagine a huge chessboard). For x[1,N],y[1,M]x \in [1, N], y \in [1, M], the cell in the xx-th row from top to bottom and the yy-th column from left to right is denoted by (x,y)(x, y). In addition, for each y[1,M]y \in [1, M], column yy has a cost cyc_y (1cy1091 \le c_y \le 10^9).

Bessie starts at cell (1,1)(1, 1). If she is currently at cell (x,y)(x, y), she can perform one of the following actions:

  • If y<My < M, Bessie can move to the next column (increase yy by 11) at a cost of x2x^2.
  • If x<Nx < N, Bessie can move to the next row (increase xx by 11) at a cost of cyc_y.

Given QQ (1Q21051 \le Q \le 2 \cdot 10^5) independent queries, each query gives (xi,yi)(x_i, y_i) (xi[1,N],yi[1,M]x_i \in [1, N], y_i \in [1, M]). Compute the minimum total cost for Bessie to move from (1,1)(1, 1) to (xi,yi)(x_i, y_i).

Input Format

The first line contains NN and MM.

The second line contains MM space-separated integers c1,c2,,cMc_1, c_2, \ldots, c_M.

The third line contains QQ.

The last QQ lines each contain two space-separated integers xix_i and yiy_i.

Output Format

Output QQ lines, one for each query, containing the answer.

Note that the integer size used in this problem may require 64-bit integers (for example, long long in C/C++).

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

Hint

Explanation for Sample 1

The output, shown in grid form, is as follows:

    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|
  *--*--*--*--*

Testdata Properties

  • Testdata 1-3 satisfy N,M2000N, M \le 2000.
  • Testdata 4-8 satisfy c2>c3>>cMc_2 > c_3 > \cdots > c_M.
  • Testdata 9-15 satisfy N2105N \le 2 \cdot 10^5.
  • Testdata 16-20 have no additional constraints.

Problem by: Benjamin Qi.

Translated by ChatGPT 5