Strong Jovsi
InterviewTime limit1sMemory limit2048 MB
Find the shortest walk on a line of l bars that picks up and delivers all n packages, with free start and end points.
- Level
Medium6 of 10
- Topics
- Prefix sum, Dynamic programming, Intervals
- Solved
- No attempts yet
Problem
Jovsi is a strong boy. Since childhood he loved machine guns and often imitated them, but for some reason he did not shout trtrtrt or bambambam. He shouted acacacacac.
Mr. Malnar is impressed by Jovsi's strength and sees him as an ideal, very cheap manual laborer. Mr. Malnar often has work to do, so he has no time for important things such as translating problems. He decided to end this by delegating his tasks to the strong Jovsi.
During the day, Mr. Malnar must complete tasks along a street with bars, numbered from to from the start to the end of the street. Any two adjacent bars are exactly meter apart. Each of Mr. Malnar's tasks is to pick up an important package at one bar and deliver it to another bar.
Mr. Malnar knows all the tasks he must complete that day in advance, and he gives the list to Jovsi. The order in which the tasks are done does not matter.
Jovsi is strong, so he can carry any number of important packages at the same time.
Jovsi is strong and smart, so he wants to complete all tasks while covering the smallest possible total distance. It does not matter at which bar he picks up the first package (since Uber will bring him there), nor at which bar he drops off the last package (since Uber will take him away from there).
Jovsi is strong and smart, but he cannot program, so he asked you to write a program that finds this minimum distance.
Input
The first line contains the natural numbers () and () from the statement. Each of the next lines contains two numbers and (, ), meaning that the -th task is to pick up a package at bar and deliver it to bar .
Output
Print the minimum distance from the statement on a single line.
Hint
The route in the first test case works as follows.
- Start at bar 2 and pick up the first package.
- Arrive at bar 1, drop off the package from bar 2, and pick up a new package.
- Arrive at bar 3 and pick up a new package.
- Arrive at bar 4 and drop off the package from bar 1.
- Arrive at bar 5 and drop off the package from bar 3.
- Arrive at bar 6 and pick up a new package.
- Arrive at bar 7 and drop off the package from bar 6.
- Arrive at bar 8 and pick up a new package.
- Arrive at bar 9 and pick up a new package.
- Arrive at bar 5 and drop off the package from bar 8.
- Arrive at bar 4, drop off the package from bar 9, and finish the route.
The total distance covered is meters.