B - 連続正解 / Consecutive Correct Answers 解説 by admin 印刷ページ
gpt-6-astra-mediumOverview
Before the first incorrect problem, output o; from the first incorrect problem onward, output x. We examine the results sequentially from the beginning while tracking whether any mistake has been made so far.
Analysis
You can receive points on the \(i\)-th problem only if you have answered all problems from the \(1\)-st to the \(i\)-th correctly.
Therefore, simply choosing o if \(A_i = 1\) and x if \(A_i = 0\) is incorrect. This is because once a mistake is made, you cannot receive points even if you answer correctly afterwards.
For example, consider the following results:
1 1 0 1 0
Points are received for the first \(2\) problems, but since the \(3\)-rd problem is answered incorrectly, no points are awarded from that point onward. The answer is the following string:
ooxxx
Although we could determine the answer by checking all previous results for each problem, this is unnecessary. Once a mistake is made, you can never return to the state where you can receive points, so maintaining a single variable to represent the state is sufficient.
Algorithm
We use a variable ok representing “no mistakes have been made so far”.
- Set
ok = Trueand initialize an empty listresto store the answer. - Inspect the result of each problem from the beginning:
- If the result is
0, setok = False. - If
okisTrue, appendotores; ifFalse, appendx.
- If the result is
- Concatenate the characters in
resand output the result.
Immediately after updating with each problem’s result, ok will be True if and only if all problems from the first to the current one are answered correctly. Since this directly matches the condition for receiving points, we can append the correct character at each position.
Complexity
- Time Complexity: \(O(N)\)
We inspect each of the \(N\) problem results once, and finally construct a string of length \(N\). - Space Complexity: \(O(N)\)
Used to store the input data and the list of characters for the answer.
Implementation Details
Update
okbefore appending the character. This is because the problem where the mistake occurred must also bex.Once
ok = False, do not set it back toTrueeven if subsequent answers are correct.In the provided code, each result is stored as a string rather than an integer, so we compare with
v == '0'.Using
''.join(res)allows you to concatenate the characters without spaces.Source Code
import sys
def main():
data = sys.stdin.read().split()
n = int(data[0])
a = data[1:1 + n]
res = []
ok = True
for v in a:
if v == '0':
ok = False
res.append('o' if ok else 'x')
sys.stdout.write(''.join(res) + '\n')
main()
This editorial was generated by gpt-6-astra-medium.
投稿日時:
最終更新: