Haybale Distribution

시간 제한2초메모리 제한1024 MB

요약
각 질의 (a,b)마다 정수 y를 골라 모든 헛간에 배송할 때의 최소 낭비량을 구해 출력한다.
난이도

어려움10점 중 8점

유형
누적 합, 정렬, 이분 탐색, 수학
정답자
아직 제출이 없습니다

문제

Farmer John is distributing haybales across the farm!

Farmer John's farm has NN (1≤N≤2⋅105)(1\le N\le 2\cdot 10^5) barns, located at integer points x_1,…,x_Nx\_1,\dots, x\_N (0≤x_i≤106)(0 \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≤106)(0 \le y \le 10^6) and then distribute one shipment to each barn.

Unfortunately, Farmer John's distribution service is very wasteful. In particular, for some a_ia\_i and b_ib\_i (1≤a_i,b_i≤106)(1\le a\_i, b\_i\le 10^6), a_ia\_i haybales are wasted per unit of distance left each shipment is transported, and b_ib\_i haybales are wasted per unit of distance right each shipment is transported. Formally, for a shipment being transported from point yy to a barn at point xx, the number of haybales wasted is given by

{a_i⋅(y−x)if y≥x b_i⋅(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⋅105)(1\le Q\le 2\cdot 10^5) independent queries each consisting of possible values of (a_i,b_i)(a\_i,b\_i), please help Farmer John determine the fewest amount of haybales that will be wasted if he chooses yy optimally.

입력

The first line contains NN.

The next line contains x_1…x_Nx\_1\dots x\_N.

The next line contains QQ.

The next QQ lines each contain two integers a_ia\_i and b_ib\_i.

출력

Output QQ lines, the iith line containing the answer for the iith query.

예제1

  1. 예제 1

    입력
    5
    1 4 2 3 10
    4
    1 1
    2 1
    1 2
    1 4
    
    예상 출력
    11
    13
    18
    30