#P1643. Roller-coaster
Roller-coaster
Problem Description
A train starts from the starting point with an initial height of and travels to the right at a constant speed of (i.e., it moves 1 unit of horizontal distance per second). The departure time of the train is a given constant (i.e., it departs from the starting point at time ). Track construction can begin at time .
There are track segments to be constructed, numbered to . Each track segment is described by three integer parameters:
- Length : a positive integer, representing the horizontal distance of the track segment.
- Height change : an integer, representing the change in height after the train travels through this track segment. If , it is an uphill segment (height increases by ); if , it is a downhill segment (height decreases by ).
- Construction time : a positive integer, representing the time required to construct this track segment.
You need to determine the traveling order of these segments (the order in which the train passes through them) and the construction order (the order in which they are built).
Constraints
- Construction order constraint: Only one track segment can be constructed at a time, and construction cannot be interrupted. For the -th segment in the traveling order, it must be completed before the train arrives at the starting point of that segment, i.e., its completion time the train's arrival time at the starting point of that segment.
- Non-negative height: At any moment during the journey, the height of the train must not fall below .
- Final height zero: After traveling through all track segments, the train's height must be exactly .
Objective
Among all traveling orders and construction plans that satisfy the above conditions, minimize the maximum height reached by the train during the journey. If no feasible solution exists, output .
Input Format
The first line contains two integers .
The next lines each contain three integers .
Output Format
Output an integer representing the minimum possible maximum height, or if no solution exists.
Examples
Sample Input 1
2 5
2 1 3
1 -1 2
Sample Output 1
1
Explanation: Both track segments can be completed before departure (total construction time ). Traveling uphill first and then downhill results in a maximum height of .
Sample Input 2
7 20
3 2 3
4 3 4
2 -1 2
3 -2 3
2 1 2
1 -2 1
2 -1 2
Sample Output 2
3
Explanation: By following the traveling order (i.e., track segment 2, track segment 4, track segment 1, track segment 3, track segment 5, track segment 7, track segment 6), the height never exceeds throughout the journey, and this value is optimal.
Sample Input 3
7 20
3 2 3
4 3 4
2 -1 2
3 -2 3
2 1 2
1 2 1
2 -1 2
Sample Output 3
-1
Explanation: It is impossible to achieve a final height of zero, so no solution exists.
Constraints
Related
In following contests: