Laser Sculpting
Time limit2sMemory limit512 MB
Given a block's height profile, count the number of horizontal 1 mm laser sweeps needed to carve it into the target shape.
- Level
Medium5 of 10
- Topics
- Simulation, Implementation, Greedy
- Solved
- No attempts yet
Problem
Since the laser was invented in 1958, it has been used in a huge variety of applications, among them electronic equipment, surgical instruments, and weapons.

The figure above is a schematic diagram of a machine that sculpts a solid block of material with a laser. The machine has a laser emitter that travels horizontally to the right and to the left at constant speed. When the emitter is switched on while it travels, a layer of constant thickness is vaporised and removed from the block along the stretch where the laser was on.
The figure below illustrates the sculpting process. Part (a) is a block 5 mm high and 8 mm long at the start of the process, part (b) is the shape the sculpted block has to end up with, and part (c) is the order in which the layers come off, assuming that each sweep removes a layer 1 mm thick. The first sweep removes the piece numbered 1, the second sweep removes the piece numbered 2, and so on. During the process the laser was switched on 7 times in total, once for each piece removed.

Write a program that reads the height of the block, the length of the block, and the final shape the block has to end up with, then determines how many times in total the laser has to be switched on.
Input
The input contains several test cases. Each test case has two lines.
The first line has the height and the length of the block to be sculpted, separated by a single space. Both are in millimetres (, ).
The second line has integers separated by spaces. The value is the final height of the block, in millimetres, over the stretch between position and position along the length ().
Along the stretch where the laser is on, every sweep removes a layer 1 millimetre thick from the block.
The last line of the input has only two zeros, separated by a single space.
Output
For each test case print a single line with one integer, the number of times the laser has to be switched on to sculpt the block into the given shape.