B - ビルの高さ / Building Heights Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
The number of #s contained in each column is the height of the building in that column. Count the #s for each column and print them from left to right.
Analysis
In the problem statement, the height of a building is defined as “the number of #s contained in that column.” Therefore, we can find the heights by examining every cell in each column and incrementing the count by \(1\) whenever we find a #.
For example, consider the following grid:
...
.#.
##.
###
The number of #s in each column from left to right is \(2, 3, 1\), so the output is as follows:
2 3 1
Since \(H, W \leq 10\) in this problem, a naive approach of checking every cell is well within the time limit. No optimization is necessary.
Note, however, that you must count column by column, not row by row. Also, the constraints do not guarantee that #s are contiguous, so even if a . appears in the middle of a column, you should not terminate the check early and must inspect all rows in that column.
Algorithm
- Read \(H, W\), and the \(H\) strings representing the grid.
- For each column from the leftmost to the rightmost column, do the following:
- Check the \(H\) cells from top to bottom in that column.
- Count the number of
#s and set it as the building height for that column.
- Print the \(W\) computed heights separated by spaces.
Since we count all #s in every column without omission, each cell exactly once, we can correctly determine the building heights as defined in the problem statement.
Complexity
- Time Complexity: \(O(HW)\)
For each of the \(W\) columns, we check \(H\) cells. - Space Complexity: \(O(HW)\)
\(O(HW)\) space is used to store the input grid, and \(O(W)\) space is used for the list of heights.
Implementation Notes
Since Python uses \(0\)-based indexing, g[i][j] represents the cell in the \((i+1)\)-th row from the top and \((j+1)\)-th column from the left.
The following snippet in the code:
sum(1 for i in range(h) if g[i][j] == '#')
computes the height of column j by inspecting each row in column j and adding \(1\) whenever a # is found.
By evaluating this with for j in range(w) from left to right, we construct the list of heights.
Additionally, using print(*list) allows you to print each element of the list separated by spaces on a single line.
Source Code
# 問題文から独立に実装
h, w = map(int, input().split())
g = [input() for _ in range(h)]
print(*[sum(1 for i in range(h) if g[i][j] == '#') for j in range(w)])
This editorial was generated by gpt-6-astra-medium.
posted:
last update: