A - 石取りゲーム / Stone Taking Game 解説 by admin
GPT 5.2 HighOverview
Since exactly 1 stone must be taken on each turn, the outcome is determined solely by “how many total moves are played (= the parity of the total number of stones).”
Analysis
In this game, the only possible action per turn is “take 1 stone from some pile.” That is,
- The number of stones removed per move is always 1
- The total number of moves until the game ends is always \(A_1 + A_2 + \cdots + A_N\) (the total number of stones)
The total number of moves does not change regardless of which pile is chosen at each step.
Therefore, the aspect of “both players playing optimally” is actually irrelevant:
- If the total number of moves is odd, the first player (Takahashi) makes the last move → Takahashi wins
- If the total number of moves is even, the second player (Aoki) makes the last move → Aoki wins
Why a Naive Approach Fails
If we simulate “taking 1 stone at a time,” since \(A_i \le 10^9\), the total number of moves can be up to nearly \(10^{14}\), which obviously won’t finish in time (TLE).
What we need is not the total number of stones itself, but only its parity (\(\bmod 2\)).
Efficiently Computing the Parity
The parity of the total sum can be obtained by XOR-ing the parity of each \(A_i\):
- Parity of \(A_1 + \cdots + A_N\) \(=\) \((A_1 \bmod 2) \oplus \cdots \oplus (A_N \bmod 2)\)
Example: \(A = [2, 5, 4]\)
The parity is \(0 \oplus 1 \oplus 0 = 1\) (odd), so Takahashi wins.
Indeed, the total is \(2+5+4=11\), which is odd.
Algorithm
- Initialize a variable
parityto \(0\). - For each pile, take the lowest bit of \(A_i\) (
A_i & 1) and XOR it intoparity. - At the end, if
parity = 1the total is odd, so outputTakahashi; if0, outputAoki.
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(1)\)
Implementation Notes
Even if you compute the actual sum, Python integers won’t overflow, but since we only need the parity for this problem, we can handle it efficiently with
x & 1and XOR.Since the input is large, we use
sys.stdin.buffer.read()for fast reading.Source Code
import sys
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
n = data[0]
a = data[1:1+n]
parity = 0
for x in a:
parity ^= (x & 1)
sys.stdout.write("Takahashi\n" if parity else "Aoki\n")
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
投稿日時:
最終更新: