公式

A - 駐車場の整理 / Parking Lot Organization 解説 by admin

Qwen3-Coder-480B

Overview

This is a problem where we need to find the minimum cost to move cars that are outside the parking lot into the parkable area.

Analysis

In this problem, each car can be moved independently, and the cost equals the distance moved. Therefore, for each car, if it is outside the parkable area \([0, M]\), the optimal strategy is to move it to the nearest edge of the parkable area (\(0\) or \(M\)).

For example, suppose a car is at coordinate \(-5\). It is to the left of the parking lot, and moving it to coordinate \(0\) is the shortest distance. Similarly, a car at coordinate \(M+3\) only needs to be moved to coordinate \(M\).

In this way, each car should optimally move “to \(0\) if its coordinate is negative” or “to \(M\) if its coordinate is greater than \(M\)”. Cars already inside the parking lot do not need to move.

A naive approach, such as trying to move cars one by one to search for the optimal arrangement, would result in an enormous computational cost. Instead, this problem can be solved with a simple method: “just check whether each car’s current position is outside the range, and add the corresponding cost.”

Algorithm

  1. Check each car’s coordinate \(A_i\) in order.
  2. If \(A_i < 0\), the car needs to move to coordinate \(0\), so add \(-A_i\) to the cost.
  3. If \(A_i > M\), the car needs to move to coordinate \(M\), so add \(A_i - M\) to the cost.
  4. Otherwise, the cost does not increase.
  5. Output the final total cost.

Complexity

  • Time complexity: \(O(N)\)
  • Space complexity: \(O(1)\) (excluding the input array)

Implementation Notes

  • Examine each car’s coordinate one by one, and compute the cost only when it is outside the range.

  • The logic is simple: move to \(0\) when the position is negative, and move to \(M\) when it exceeds \(M\).

  • No sorting or searching is required, so the solution can be processed quickly and simply.

    Source Code

N, M = map(int, input().split())
A = list(map(int, input().split()))

total_cost = 0
for a in A:
    if a < 0:
        total_cost += -a
    elif a > M:
        total_cost += a - M

print(total_cost)

This editorial was generated by qwen3-coder-480b.