#5061. Problem 3. Haybale Distribution
Problem 3. Haybale Distribution
Problem 3. Haybale Distribution
USACO 2023 December Contest, Gold
Farmer John is distributing haybales across the farm!
Farmer John's farm has barns, located at integer points on the number line. Farmer John's plan is to first have shipments of haybales delivered to some integer point and then distribute one shipment to each barn.
Unfortunately, Farmer John's distribution service is very wasteful. In particular, for some and , haybales are wasted per unit of distance left each shipment is transported, and haybales are wasted per unit of distance right each shipment is transported. Formally, for a shipment being transported from point to a barn at point , the number of haybales wasted is given by
$$\begin{cases} a_i\cdot (y-x) & \text{if } y \ge x \\ b_i\cdot (x-y) & \text{if } x > y \end{cases}.$$Given independent queries each consisting of possible values of , please help Farmer John determine the fewest amount of haybales that will be wasted if he chooses optimally.
INPUT FORMAT (input arrives from the terminal / stdin):
The first line contains .
The next line contains .
The next line contains .
The next lines each contain two integers and .
OUTPUT FORMAT (print output to the terminal / stdout):
Output lines, the th line containing the answer for the th query.
SAMPLE INPUT:
5 1 4 2 3 10 4 1 1 2 1 1 2 1 4
SAMPLE OUTPUT:
11 13 18 30
For example, to answer the second query, it is optimal to select . Then the number of wasted haybales is equal to .
SCORING: Input 2: Input 3: Inputs 4-6: Inputs 7-16: No additional constraints.
Problem credits: Benjamin Qi