B - 連続正解 / Consecutive Correct Answers 解説 by admin
gpt-6-astra-mediumOverview
Output o for the problems up to the first mistake, and x for the first problem answered incorrectly and all subsequent problems. We can process the problems in order while keeping track of whether a mistake has been made so far.
Analysis
You receive points for the \(i\)-th problem only if you have answered all problems from the \(1\)-st to the \(i\)-th problem correctly.
Therefore, simply outputting o if \(A_i = 1\) and x if \(A_i = 0\) is not correct. This is because once you make a mistake, you cannot earn points even if you answer subsequent problems correctly.
For example, consider the following results:
1 1 0 1 0
You get points for the first \(2\) problems, but make a mistake on the \(3\)-rd problem. After that, even though the \(4\)-th problem is answered correctly, you do not receive points for it, so the output is as follows:
ooxxx
What is needed here is not remembering all past results, but only the information of “whether any mistake has been made so far.” By maintaining this with a boolean flag ok, we can solve the problem by checking each problem once.
Algorithm
- Initialize the answer string
resto an empty string and setoktotrue. - Read the results of each problem from left to right and perform the following:
- If
okistrueand the current result is \(1\), appendotores. - Otherwise, set
oktofalseand appendxtores.
- If
- After processing all problems, output
res.
Before processing each problem, ok represents “whether all previous problems were answered correctly.” Therefore, by appending o only when ok is true and the current problem is also answered correctly, we can directly replicate the condition for earning points.
Complexity
- Time Complexity: \(O(N)\)
Each problem is processed once. - Space Complexity: \(O(N)\)
We store the output string of length \(N\). The additional working memory required is \(O(1)\).
Implementation Notes
Initially, no mistakes have been made yet, so initialize
oktotrue.Once
okbecomesfalse, it must not be set back totrue, even if a subsequent problem is answered correctly.The first problem answered incorrectly should also be
x.If all problems are answered correctly, the output will be all
os; if the first problem is answered incorrectly, it will be allxs.There is no need to store the results in an array; they can be processed immediately upon reading, as in the sample code.
Source Code
// 問題文から独立に実装: フラグを持ち回る
#include <iostream>
#include <string>
int main() {
int n; std::cin >> n;
std::string res;
bool ok = true;
for (int i = 0; i < n; ++i) {
int a; std::cin >> a;
if (ok && a == 1) res += 'o';
else { ok = false; res += 'x'; }
}
std::cout << res << std::endl;
}
This editorial was generated by gpt-6-astra-medium.