Sticks
Time limit1sMemory limit128 MB
You keep a connected set of sticks that meet only at endpoints without crossing to maximize total length.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Graph, Geometry, Sorting
- Solved
- No attempts yet
Problem
There is a game played with sticks of various lengths. Before the game starts, you draw two parallel horizontal lines a distance apart on a desk, and you place each stick so that its two ends lie one on the upper line and one on the lower line. Several stick ends may meet at a single point on a line, but no two sticks completely overlap.
Each stick is written as , where is its coordinate on the upper line and is its coordinate on the lower line. In Figure 1 below, stick is and stick is .

The goal of the game is to remove some of the placed sticks so that the remaining sticks form a single zigzag line satisfying all three conditions below.
- The sticks touch only at endpoints and otherwise do not cross one another.
- No point has three or more stick ends meeting at it.
- All sticks are connected to one another.
The winner is whoever makes the longest zigzag line. The length of a zigzag line is the sum of the lengths of its sticks, and the length of one stick is its horizontal distance plus its vertical distance between the two endpoints. For a stick the horizontal distance is and the vertical distance is , the gap between the two lines. In the figure above, the stick lengths are as follows.
For example, in Figure 1 keeping only sticks gives a zigzag line that satisfies all three conditions, with length . Keeping only sticks also satisfies all three conditions, with length . Keeping only sticks violates condition 1, keeping only violates condition 2, and keeping only violates condition 3. The longest zigzag line is made of sticks with length .
Given the initial arrangement of the sticks, write a program that finds the length of the longest zigzag line that can be formed.
Input
The first line contains two integers and separated by a space: the number of sticks and the gap between the two horizontal lines. Here and .
Each of the next lines contains two integers and separated by a space, describing one stick . Here . No two sticks in the input completely overlap.
Output
Print the length of the longest zigzag line on a single line.
Hint
Intermediate values and the answer can exceed the range of a 32-bit integer, so using a 64-bit integer type is recommended.