Under construction

Still being built. Things may change

Haybale Distribution

Interview

Time limit2sMemory limit1024 MB

Summary
Given N barn positions and Q pairs (a, b), find for each pair the minimum total haybale waste when choosing a delivery point y in [0, 10^6].
Level

Medium5 of 10

Topics
Sorting, Prefix sum, Binary search, Greedy
Solved
No attempts yet

Problem

Farmer John is distributing haybales across the farm.

Farmer John's farm has NN barns (1≤N≤2⋅1051\le N\le 2\cdot 10^5), located at integer points x1,…,xNx_1,\dots, x_N (0≤xi≤1060 \le x_i \le 10^6) on the number line. Farmer John's plan is to first have NN shipments of haybales delivered to some integer point yy (0≤y≤1060 \le y \le 10^6), and then distribute one shipment to each barn.

Unfortunately, Farmer John's distribution service is very wasteful. For some aia_i and bib_i (1≤ai,bi≤1061\le a_i, b_i\le 10^6), aia_i haybales are wasted per unit of distance a shipment travels left, and bib_i haybales are wasted per unit of distance it travels right. For a shipment transported from point yy to a barn at point xx, the number of haybales wasted is

{ai⋅(y−x)if y≥xbi⋅(x−y)if x>y.\begin{cases} a_i\cdot (y-x) & \text{if } y \ge x \\ b_i\cdot (x-y) & \text{if } x > y \end{cases}.

Given QQ (1≤Q≤2⋅1051\le Q\le 2\cdot 10^5) independent queries, each giving a pair (ai,bi)(a_i,b_i) of possible values, determine the fewest haybales that will be wasted if Farmer John chooses yy optimally.

Input

The first line contains NN. The next line contains x1…xNx_1\dots x_N. The next line contains QQ. The next QQ lines each contain two integers aia_i and bib_i.

Output

Output QQ lines. The iith line contains the answer for the iith query.

Examples1

  1. Example 1

    Input
    5
    1 4 2 3 10
    4
    1 1
    2 1
    1 2
    1 4
    
    Expected output
    11
    13
    18
    30