Marathon 2
InterviewTime limit1sMemory limit256 MB
Run checkpoints 1 to N in order while skipping at most K middle checkpoints to minimize total Manhattan distance.
- Level
Medium5 of 10
- Topics
- Dynamic programming
- Solved
- No attempts yet
Problem
Farmer John decided that his cows were out of shape, so he organized a marathon for them. Bessie, his favorite cow, is going to run it.
The course consists of checkpoints. The marathon starts at checkpoint 1, visits every checkpoint in index order, and finishes at checkpoint . Bessie is lazy. She will run the race, but she wants to secretly skip up to of the checkpoints in the middle. Skipping checkpoint 1 or checkpoint would be far too obvious, so she leaves those two alone.
If Bessie skips at most checkpoints, what is the shortest distance she has to run?
The race is held in the middle of the city, so distances are taxicab (Manhattan) distances. The distance between and is , where denotes absolute value.
Input
The first line contains the number of checkpoints and the number of checkpoints Bessie may skip (, ).
Each of the next lines contains two integers. The first integer on line is the coordinate of checkpoint and the second is its coordinate (, ).
Two checkpoints may share the same coordinates. When Bessie skips a checkpoint she skips only that index, not every checkpoint located at that point.
Output
Print the shortest distance Bessie can run while skipping at most checkpoints.
Hint
In the first example Bessie skips checkpoints 2 and 4, so she runs , , for a total distance of 4. No route is shorter.