Manure Teleporter
Time limit2sMemory limit512 MB
Choose y to minimize the total driving distance when each pile can be hauled directly or via a teleporter from 0 to y.
- Level
Medium7 of 10
- Topics
- Greedy, Math, Sorting, Implementation
- Solved
- No attempts yet
Problem
The farm chore Farmer John dislikes most is hauling large amounts of manure. To cut the work down he builds a manure teleporter. Instead of driving a cart behind his tractor between two points, he sends manure from one location to another instantly.
Farmer John's farm lies along a single straight road, so every location on it is described by one coordinate along that road, a point on the number line. A teleporter is described by two numbers and : manure brought to location is transported instantly to location .
Farmer John puts one endpoint at and has to choose where the other endpoint goes. There are piles of manure on the farm (). Pile must be moved from position to position , and each pile is transported separately. Let be the distance Farmer John drives with pile in his tractor. Hauling it directly gives . Using the teleporter means driving from to and then from to , which gives . Farmer John takes the shorter of the two routes. The same is used while every pile is transported.
Choose so the sum of the is as small as possible, and report that sum.
Input
The first line contains . Each of the next lines contains and , both integers in the range to . The values are not necessarily distinct.
Output
Print the minimum sum of the as a single integer. The value can exceed the range of a 32-bit integer, so use a 64-bit integer type in languages that need one.
Hint
In the first example, setting gives , and . Any between and gives the same sum.