Fireworks in RightAngleles
Time limit1sMemory limit128 MB
Choose a vertical launch street V minimizing total Manhattan-like walking distance for citizens to reach nearest allowed point on the two crossing streets, respecting a safety gap S.
- Level
Hard8 of 10
- Topics
- Binary search, Greedy, Math
- Solved
- No attempts yet
Problem
In the city of RightAngleles the streets form an infinite square grid: every pair of streets is either parallel or perpendicular, and neighboring parallel streets are exactly one unit apart. Streets running West-East are called horizontal and are numbered by consecutive integers from South to North; streets running South-North are called vertical and are numbered by consecutive integers from West to East. Each intersection is identified by the number of its horizontal street and the number of its vertical street.
Every citizen lives at the intersection where their house entrance is located, and several citizens may live at the same intersection.
The mayor wants to hold a fireworks display at the intersection of the main horizontal street (numbered ) and some vertical street . The fireworks are visible only along the two streets that meet there — the main horizontal street and vertical street . For safety, every spectator must stand at least units away from the launch intersection. Concretely, a citizen may watch the display from either:
- an intersection on the main horizontal street whose vertical street number differs from by at least , or
- an intersection on vertical street whose horizontal street number is at least away from .
For example, when the display may be watched from any intersection of the main horizontal street except those lying on vertical streets , , and , and from any intersection of vertical street except those lying on horizontal streets , , and .
Citizens move only along the streets, so the distance a citizen walks to reach a watching spot equals the number of unit segments travelled. Each interested citizen walks to a nearest allowed watching spot, and the mayor chooses the vertical street so that the total distance walked by all citizens is as small as possible.
Write a program that computes this minimum possible total distance.
Input
The first line contains two positive integers and separated by a space: the number of citizens () and the safety distance ().
Each of the next lines contains two integers and separated by a space (): the horizontal street number and the vertical street number of the intersection where the -th citizen lives.
Output
Print a single integer: the minimum total distance (in units) that the citizens must walk in order to watch the fireworks.