Space Invaders
InterviewTime limit2sMemory limit1024 MB
Given aliens stacked in n columns and a cannon starting at column p, find the minimum number of move and fire actions to destroy every alien.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Greedy, Array, Implementation
- Solved
- No attempts yet
Problem
Petya wrote his own version of the well-known game <>. The game works as follows. Ships of space invaders attack the Earth. They are lined up in rows at the top of the screen. The player controls a laser cannon, which is at the bottom edge of the screen in one of the columns. In one action the player can move the cannon left or right, or fire vertically upward. If the player fires, the shot destroys the nearest alien ship in the column where the cannon is located.

Unlike the original game, in Petya's version the alien ships stay in place and cannot shoot, so the player cannot lose. Help Petya destroy all the alien ships in the minimum number of actions.
Input
The first line of the input file contains the numbers and , the number of columns and the number of the column where the cannon is initially located (, ). The second line contains numbers , where is the number of aliens in the -th column ().
Output
Output to the output file a single number: the minimum number of actions needed to destroy all the aliens.