B - ビルの高さ / Building Heights Editorial by admin Editorial for printing
swe-2-highEditorial
For each column \(j\) (\(1 \leq j \leq W\)), we simply count the number of # characters it contains. By definition, that count is the height of the \(j\)-th building.
Algorithm
Initialize a counter array \(\mathrm{ans}\) of length \(W\) with zeros. Read the \(H\) strings \(S_1, \ldots, S_H\) one by one; for each row, if the \(j\)-th character is #, increment \(\mathrm{ans}[j]\) by one. After processing all rows, print \(\mathrm{ans}[1], \ldots, \mathrm{ans}[W]\) in order, separated by spaces.
Proof of correctness
Fix an arbitrary column \(j\). For every \(i = 1, \ldots, H\), the algorithm inspects the \(j\)-th character of \(S_i\) exactly once and increments \(\mathrm{ans}[j]\) if and only if it is #. Hence the final value of \(\mathrm{ans}[j]\) equals the cardinality of \(\{i \mid \text{the } j\text{-th character of } S_i \text{ is } \#\}\), i.e., the number of # in column \(j\). By the statement’s definition, this is exactly the height of the \(j\)-th building. Since \(j\) was arbitrary, all heights are computed correctly, and they are printed in left-to-right order. No cell is skipped or counted twice, so the counts are exact.
Complexity
- Time: each cell is examined once, so \(O(HW)\).
- Space: \(O(W)\) for the counter array. An implementation that keeps all input rows uses \(O(HW)\) space for the input; processing rows one at a time keeps auxiliary space at \(O(W)\).
Since \(H, W \leq 10\), any implementation is fast enough.
Tie-breaking
Each building’s height is uniquely determined, so there are no ties to break. The output order is fixed as left-to-right column order.
posted:
last update: