#P7625. Minimum Ship Movement

    ID: 20818 Type: Default 1000ms 256MiB

Minimum Ship Movement

Minimum Ship Movement

Mirko is obsessed with a video game. In the game, the screen is divided into \(N\) columns and at the bottom there is a ship that spans \(M\) consecutive columns. The ship can be moved left or right, but it must always remain completely inside the screen. Initially, the ship occupies the leftmost \(M\) columns.

Apples fall from the top of the screen one at a time. Each apple starts falling from one of the \(N\) columns and moves straight down. When an apple reaches the bottom of the screen, the next apple falls. An apple is considered "picked up" if, when it reaches the bottom, its column is covered by the ship.

Your task is to pick up all apples while minimizing the total distance the ship moves. At the beginning, the ship is positioned at columns \(1\) to \(M\). When an apple drops at column \(x\), if \(x\) is already within the ship's current position, no move is needed. Otherwise:

  • If \(x < L\) where \(L\) is the leftmost column currently covered by the ship, move the ship left so that its leftmost column becomes \(x\) (a movement of \(L - x\)).
  • If \(x > R\) where \(R = L + M - 1\) is the rightmost column of the ship, move the ship right so that its rightmost column becomes \(x\) (a movement of \(x - R\)). In this case, update \(L = x - M + 1\).

Calculate the minimum total distance the ship must travel to pick up all the apples.

inputFormat

The input consists of multiple lines:

  • The first line contains two integers \(N\) and \(M\) separated by a space, representing the number of columns on the screen and the width of the ship, respectively.
  • The second line contains an integer \(K\), the number of apples.
  • The third line contains \(K\) integers, each representing the column from which an apple falls, in the order they fall.

outputFormat

Output the minimum total distance that the ship must move to pick up all the apples.

sample

10 3
3
9 4 2
11

</p>