Editorial for COCI '14 Contest 5 #2 Zmija
Submitting an official solution before solving the problem yourself is a bannable offence.
Let's denote the lower left corner of the screen (the snake's initial position) with the coordinate and the upper right corner with the coordinate . Let be the largest row number that contains at least one apple. It is evident that the number of presses of button B
is equal to .
We are left with the problem of the number of presses of button A
. Let's assume that the snake is located at row and column . Depending on the parity of number , the snake is facing to the left (odd ) or to the right (even ). Let's analyze the necessary steps the snake must do in the given situation.
If the snake is facing to the left and row contains an apple that is located at a column number smaller than , it is necessary to keep pressing the A
button until we get to at least that apple. Additionally, if the row above (numbered ) contains an apple that is located at a column number smaller than , it is necessary to keep pressing the A
button until we get to at least that column (otherwise, we won't be able to eat that apple). Only then can we press button B
and move upwards.
Analogously, if the snake is facing to the right, it is necessary to keep pressing the A
button to position the snake to at least the maximum column number that contains an apple in rows or .
Is it possible to reduce the number of necessary steps in one of the following rows by exceeding the number of necessary steps in the current row? It is visible that we increase (or don't change) the number of necessary steps in the row above when we exceed the number of necessary steps in the current row. Inductively, it is clear that by using necessary movements in each row we will obtain the path of optimal length.
Comments