Official

C - 駐車場の車庫入れ / Parking Lot Guidance Editorial by admin

Qwen3-Coder-480B

Overview

We simulate the process of parking cars as they arrive at a parking lot in order, and determine the number of cars that were successfully parked.

Analysis

This problem is a simulation problem where we place cars in the parking lot according to the rules, in the order they arrive.

Each car \(i\) has a preferred parking space \(P_i\), and parks as follows:

  1. If the preferred space is empty, park there.
  2. Otherwise, among the spaces with numbers larger than the preferred space, park in the empty space with the smallest number.
  3. If no such space exists, the car cannot park.

This can be solved by straightforwardly simulating this process. The key point is efficiently managing whether each space is already occupied. By using an array (such as a list) to track whether each parking space is occupied, we can determine the result in constant or linear time for each car.

If we perform a full search of the parking lot state each time, the worst case is \(O(NM)\), but since the constraints are \(N, M \leq 100\), this is more than fast enough.

Algorithm

We perform the simulation with the following steps:

  1. Prepare an array parking to manage the state of the parking lot. If parking[i] is True, then parking space \(i\) is occupied.
  2. For each car \(i\)’s preferred parking space \(P_i\):
    • First check if \(P_i\) is empty; if so, park there.
    • If it is occupied, search from \(P_i+1\) to \(M\) and park in the first empty space found.
    • If neither is possible, the car fails to park.
  3. Count and output the number of cars that successfully parked.

Complexity

  • Time complexity: \(O(NM)\)
    Because for each car, we may need to scan up to \(M\) parking spaces.
  • Space complexity: \(O(M)\)
    The size of the array managing the parking lot state.

Implementation Notes

  • Since parking space indices range from 1 to M, allocate the parking array with length \(M+1\) and use parking[1..M].

  • When processing each car, if the preferred space is occupied and we search for a larger-numbered space, make sure to break out of the loop once an empty space is found.

    Source Code

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

parking = [False] * (M + 1)  # parking[1..M] を使う
count = 0

for p in P:
    if not parking[p]:
        parking[p] = True
        count += 1
    else:
        for i in range(p + 1, M + 1):
            if not parking[i]:
                parking[i] = True
                count += 1
                break

print(count)

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