Official

B - ビルの高さ / Building Heights Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

The height of the building in each column is the number of #s contained in that column. We inspect all cells, count the number of #s for each column, and output them in order from left to right.

Analysis

The key point is that the height of a building is defined as “the number of #s contained in that column.” Therefore, there is no need to check the positions of the #s or whether they are contiguous.

For example, consider the following grid:

...
.#.
##.

The number of #s in each column from left to right is \(1, 2, 0\), so the output is as follows:

1 2 0

For this problem, a naive approach of checking every cell once is sufficient. Since \(H, W \leq 10\), there are at most \(100\) cells to inspect, so there is no need to worry about the time limit.

However, note that we must count column by column, not row by row. This can be achieved by iterating through the rows and incrementing the counter for the column to which each found # belongs.

Algorithm

  1. Prepare an array ans of length \(W\) and initialize all elements to \(0\). ans[j] represents the height of the \((j+1)\)-th building from the left.
  2. For each row, inspect all characters from left to right.
    • If the character is #, increment ans[j] corresponding to that column by \(1\).
    • If the character is ., do nothing.
  3. Output the elements of ans from the beginning, separated by spaces.

Since each cell is checked once and the counter for the corresponding column is incremented only when it is a #, the count of #s in each column will be correctly stored in ans at the end.

Complexity

  • Time complexity: \(O(HW)\)
    Each of the \(H \times W\) cells is inspected once.
  • Space complexity: \(O(HW + W)\)
    The provided code uses \(O(HW)\) space to store the input strings and \(O(W)\) space for the answer array. The auxiliary space excluding the input storage is \(O(W)\).

Implementation Notes

  • Python uses \(0\)-based indexing. S[i][j] represents the cell in the \((i+1)\)-th row from the top and the \((j+1)\)-th column from the left.

  • When a # is found, increment ans[j] using the column index j, not the row index i.

  • By initializing ans entirely with \(0\), the height of columns without any # will also correctly be \(0\).

  • Using ' '.join(map(str, ans)), you can convert the integers to strings and output them separated by spaces.

    Source Code

import sys


def main():
    data = sys.stdin.read().split()
    H = int(data[0])
    W = int(data[1])
    S = data[2:2 + H]
    ans = [0] * W
    for i in range(H):
        row = S[i]
        for j in range(W):
            if row[j] == '#':
                ans[j] += 1
    print(' '.join(map(str, ans)))


main()

This editorial was generated by gpt-6-astra-medium.

posted:
last update: