Editorial for Baltic OI '01 P3 - Box of Mirrors
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
The correct solution is a greedy algorithm, that tries to put mirrors in such way that every light beam goes as much as possible upwards. We will successively track beams lighted into gaps with numbers .
Let us consider the following algorithm:
- Let be the current column and row of the tracked beam. Let be the column and row of the gap through which the beam should leave.
- If and then stop.
- If beam goes vertically go to point 5.
- If there is a mirror above the current position and or go one cell to the right: . Otherwise, place mirror in the cell and go one cell up: . Go back to point 2.
- If there is a mirror in the current cell, go right: . Otherwise go up: . Go back to point 2.
To prove the correctness of this algorithm, we will consider the only bad situation:
The beam should leave with the gap above, but on the way there is a mirror . This situation can not occur because there is no light reflected by the upper side of a mirror . And in our algorithm the mirror is placed only when the beam is reflected.
Comments