A - スイッチの切り替え / Flipping Switches 解説 by admin
Qwen3-Coder-480BOverview
Given the initial state of each light and the number of times each switch is pressed, determine the final ON/OFF state of each light.
Analysis
In this problem, each light can be processed independently, so we can consider them individually.
The key observation is that the state of a light is determined by the parity (even or odd) of the number of switch presses \(K_i\): - If the switch is pressed an even number of times, the light’s state does not change (it returns to its original state) - If the switch is pressed an odd number of times, the light’s state is toggled
For example, if the initial state is Yes (ON) and \(K_i = 3\) (odd), the final state will be No (OFF).
By utilizing this property, we don’t need to actually press the switch \(K_i\) times — we only need to check whether \(K_i\) is odd. This allows us to efficiently handle even very large values of \(K_i\) (up to \(10^9\)).
A naive approach (e.g., toggling the state \(K_i\) times in a loop) will not finish in time when \(K_i\) is large (TLE).
Algorithm
- For each light, repeat the following:
- If the initial state \(S_i\) is
Yes, set it to ON; ifNo, set it to OFF - If the number of presses \(K_i\) is odd, toggle the current state
- Record the final state
- If the initial state \(S_i\) is
- Output the final state of all lights
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(N)\)
Implementation Notes
After reading the input as a string, convert it to an integer (
K = int(K))Toggling the state can be easily done using the
notoperatorRather than outputting everything at once, it is more efficient to store each result in a list and join them with newlines at the end
Source Code
N = int(input())
results = []
for _ in range(N):
S, K = input().split()
K = int(K)
# 初期状態が "Yes" (ON) かどうか
is_on = (S == "Yes")
# K回押した後の状態: Kが偶数なら変化なし、奇数なら反転
if K % 2 == 1:
is_on = not is_on
# 最終状態を結果に追加
results.append("Yes" if is_on else "No")
print("\n".join(results))
This editorial was generated by qwen3-coder-480b.
投稿日時:
最終更新: