B - ビルの高さ / Building Heights Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
The number of #s in each column represents the height of the building standing in that column. By reading the grid row by row, we can count the number of #s in each column and print the counts 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, the answer can be found by inspecting every cell and incrementing the counter for the corresponding column whenever a # is found.
For example, consider the following grid:
..#.
#.##
####
From left to right, the number of #s in each column is \(2, 1, 3, 2\), so the output is as follows:
2 1 3 2
For this problem, a naive approach of checking every cell is completely sufficient. Given the constraints, the total number of cells is at most \(10 \times 10 = 100\), which will not cause a TLE.
However, note that you must count the number of cells per column, not per row. Additionally, rather than guessing the height from the position of the first #, it is more reliable to simply count the total number directly according to the definition.
Algorithm
Prepare a counter for each column and tally the counts while reading the input.
- Prepare an array
cntof length \(W\), initializing all elements to \(0\). - Read the string
sfor each row, and for each column \(j\), do the following:- If
s[j]is#, incrementcnt[j]by \(1\). - If
s[j]is., do nothing.
- If
- Print
cnt[0]throughcnt[W-1], separated by spaces.
Each cell is examined exactly once, and only when a cell is # is the counter for the corresponding column incremented. As a result, the final value of cnt[j] is the total number of #s in the \((j+1)\)-th column from the left, which matches the desired building height.
Complexity
- Time complexity: \(O(HW)\)
Every cell across the \(H\) rows and \(W\) columns is examined once. - Space complexity: \(O(W)\)
Stores the counter array of length \(W\) and the string for the single row currently being read.
Implementation Notes
Since array and string indices in C++ start from \(0\),
cnt[j]corresponds to the \((j+1)\)-th building from the left.cntcan be initialized with all zeros asstd::vector<int> cnt(w, 0);.There is no need to store the entire grid in memory. You can update the counters as each row is read.
In the output, print a newline only after the last element, and print a space after every other element.
Source Code
// 問題文から独立に実装: 行を読みながら列ごとのカウンタに加算
#include <iostream>
#include <string>
#include <vector>
int main() {
int h, w; std::cin >> h >> w;
std::vector<int> cnt(w, 0);
for (int i = 0; i < h; ++i) {
std::string s; std::cin >> s;
for (int j = 0; j < w; ++j) if (s[j] == '#') cnt[j]++;
}
for (int j = 0; j < w; ++j) std::cout << cnt[j] << (j + 1 < w ? " " : "\n");
}
This editorial was generated by gpt-6-astra-medium.
posted:
last update: