#P9982. [USACO23DEC] Haybale Distribution G

[USACO23DEC] Haybale Distribution G

Problem Description

Farmer John is distributing haybales on his farm.

There are NN barns (1N2105)(1 \le N \le 2 \cdot 10^5) on Farmer John’s farm, located at integer points x1,,xNx_1,\ldots,x_N on a number line (0xi106)(0 \le x_i \le 10^6). Farmer John plans to transport NN truckloads of haybales to an integer point yy (0y106)(0 \le y \le 10^6), and then deliver one truckload to each barn.

Unfortunately, Farmer John’s delivery system wastes many haybales. Specifically, given some ai,bia_i, b_i (1ai,bi106)(1 \le a_i, b_i \le 10^6), for each truckload, moving one unit distance to the left wastes aia_i haybales, and moving one unit distance to the right wastes bib_i haybales. Formally, for one truckload moving from integer point yy to a barn at position xx, the number of wasted haybales is:

$$\begin{cases}a_i\cdot (y-x) & \text{if} \ y>x \\ b_i\cdot(x-y)&\text{if}\ x>y\end{cases}$$

You are given QQ independent queries (1Q2105)(1 \le Q \le 2 \cdot 10^5). Each query provides a pair (ai,bi)(a_i, b_i). Help Farmer John compute, when choosing the best yy, the minimum total number of haybales wasted.

Input Format

The first line contains NN.

The next line contains x1xNx_1 \dots x_N.

The next line contains QQ.

The next QQ lines each contain two integers ai,bia_i, b_i.

Output Format

Output QQ lines. The ii-th line contains the answer to the ii-th query.

5
1 4 2 3 10
4
1 1
2 1
1 2
1 4
11
13
18
30

Hint

Sample Explanation 1

In the second query of the sample, the best choice is y=2y = 2. The number of wasted haybales is $2(2-1) + 2(2-2) + 1(3-2) + 1(4-2) + 1(10-2) = 2 + 0 + 1 + 2 + 8 = 13$.

Test Point Properties

  • Test point 22 satisfies N,Q10N, Q \le 10.
  • Test point 33 satisfies N,Q500N, Q \le 500.
  • Test points 464-6 satisfy N,Q5000N, Q \le 5000.
  • Test points 7167-16 have no additional constraints.

Translated by ChatGPT 5