Haybale Distribution
InterviewTime limit2sMemory limit1024 MB
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 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. For some and (), haybales are wasted per unit of distance a shipment travels left, and haybales are wasted per unit of distance it travels right. For a shipment transported from point to a barn at point , the number of haybales wasted is
Given () independent queries, each giving a pair of possible values, determine the fewest haybales that will be wasted if Farmer John chooses optimally.
Input
The first line contains . The next line contains . The next line contains . The next lines each contain two integers and .
Output
Output lines. The th line contains the answer for the th query.