B - 宝物の地図 / Treasure Map Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
Check whether each row contains a T representing a treasure. If it contains a treasure, output o; otherwise, output x, listed in order from the top row to the bottom row.
Analysis
To determine the answer for a particular row, it is sufficient to inspect only that row. Whether other rows contain treasures is irrelevant.
Therefore, we check all characters in each row and count the number of Ts.
- If the count of
Tis \(0\), there is no treasure, so the answer isx. - If the count of
Tis \(1\) or more, there is a treasure, so the answer iso.
For example, if a row is ..T.T, there are \(2\) Ts, so it is o; if it is ....., there are \(0\) Ts, so it is x.
For this problem, a naive approach of checking every cell is sufficient. Since there are at most \(10 \times 10 = 100\) cells, there is no need to worry about exceeding the time limit. Note that if you set the answer to o only when there is “exactly \(1\)” treasure, rows with multiple treasures will result in a Wrong Answer, so be careful.
Algorithm
- Read \(H\) and \(W\), and initialize an empty string
ansto store the answer. - From the top row to the bottom, perform the following steps:
- Read the string
sfor that row. - Reset
cnt, which represents the number of treasures, to \(0\). - Check all \(W\) characters of
s, and incrementcntby \(1\) each time aTis found. - If
cntis \(0\), appendxtoans; otherwise, appendo.
- Read the string
- Output
ans.
Since we check all characters in each row, cnt matches the number of treasures in that row. Furthermore, because we append the results from top to bottom, we obtain the required string of length \(H\).
Complexity
- Time complexity: \(O(HW)\)
For each of the \(H\) rows, we inspect \(W\) characters. - Space complexity: \(O(H + W)\)
We store the answeransof length \(H\) and the current rowsof length \(W\).
Implementation Notes
Reset
cntto \(0\) for each row. Make sure not to carry over the count from the previous row.Since string indexing is \(0\)-based, check indices from
s[0]tos[W-1].The output requires lowercase
oandx. Be careful not to confuse them with the digit0or uppercaseO.There is no need to store the entire grid; you can process it by reading \(1\) row at a time.
Source Code
// 問題文から独立に実装: 各行の T の個数を数え、0 なら x
#include <iostream>
#include <string>
int main() {
int h, w; std::cin >> h >> w;
std::string ans;
for (int i = 0; i < h; ++i) {
std::string s; std::cin >> s;
int cnt = 0;
for (int j = 0; j < w; ++j) if (s[j] == 'T') cnt++;
ans += (cnt == 0) ? 'x' : 'o';
}
std::cout << ans << std::endl;
}
This editorial was generated by gpt-6-astra-medium.
posted:
last update: