From http://blog.csdn.net/shuangde800
Question: Click to open the link.
(Lrj Training Guide)
There are n garbage items. The coordinate of the I garbage is (XI, Yi), and the weight is WI. A robot needs to pick up all the garbage from small to large and throw it into the garbage bin (the garbage bin is at the origin (0, 0 )). A robot can pick up a few garbage items and then discard them together. However, the total weight of the garbage in its hands cannot exceed the maximum load C at any time. The walking distance between two points is the Manhattan distance (that is, the absolute value of the abscissa difference plus the absolute value of the ordinate difference ). Find the shortest distance for a robot to walk (at (0, 0) at the beginning ).
[Input format]
The number of first behavior data groups. The maximum load of the first behavior of each group of data is C (1 ≤ C ≤ 100), and the positive integer N (1 ≤ n ≤ 100 000), that is, the number of garbage; the following n rows have two non-negative integers x, y, and a positive integer W, that is, coordinates and weight (the weight cannot exceed C ).
[Output format]
The minimum length of the output path for each group of data.
Ideas
Method 1:
Sumdis [I], which indicates that the distance from 0 to> 1-> 2->...-> I is the total distance from 0 to I.
Sumweight [I] indicates the total weight of the first garbage.
Suppose we want to collect garbage from (J, I,
W (J, I) = sumweight [I]-sumweight [J-1]; indicates the total weight of garbage in the (J, I) Interval
The walking path of the robot is: 0-> J + 1->...-> I-> 0. The total distance of the path is:
Routedist (J, I) = getdis (0, j) + sumdis [I]-sumdis [J] + getdis (0, I)
If f (I) is set, it indicates that the shortest distance of the first garbage collection is reached, so status transfer can be obtained.
F (I) = min {f (J-1) + routedist (J, I ), 1 <= j <= I & sumweight [I]-sumweight [J-1]> = c}
Code 1
Method 2: optimize the priority queueThe complete expression of the above equation is: f (I) = min {f (J-1) + getdis (0, j) + sumdis [I]-sumdis [J] + getdis (I, 0) | 1 <= j <= I & sumweight [I]-sumweight [J-1]> = c}
Can be converted to: f (I) = min {f (J-1) + getdis (0, J) -sumdis [J] | 1 <=j <= I & sumweight [I]-sumweight [J-1]> = c} + sumdis [I] + getdis (I, 0)
To make the expression easier to understand, make another func (j) =
F (J-1) + getdis (0, j)-sumdis [J]).
Then the equation is f (I) = min {
Func (j) | 1 <= j <= I & W (J, I) <= c} + sumdis [I]-getdis (0, I );
To minimize f (I), you only need to minimize func (j.
Therefore, we can maintain a J to minimize func (j ).
The monotonous queue is used for optimization.
Code for the monotonous queue method: