B - カード取りゲーム / Card Taking Game Editorial by admin
Qwen3-Coder-480BOverview
In a game where Takahashi and Aoki alternately take cards to maximize their scores, we find the score difference (Takahashi’s score − Aoki’s score) when both players play optimally.
Analysis
In this game, each player tries to maximize their own score, but must also consider minimizing the opponent’s score. In other words, a minimax-style approach is needed.
However, a key characteristic of this problem is that “cards are taken in turns, and both players play optimally.” The important observation is:
- Each player’s optimal strategy is to always take the highest-scoring card remaining
This is because if there is a card of high value to both players, letting the opponent take it would be disadvantageous.
Therefore, the game proceeds as follows:
- First, sort the cards in descending order
- The first player (Takahashi) takes the cards at even indices (0, 2, 4, …)
- The second player (Aoki) takes the cards at odd indices (1, 3, 5, …)
This is the optimal strategy.
For example, if the cards are [3, 1, 4]:
- After sorting: [4, 3, 1]
- Takahashi takes 4 and 1 for a total of 5
- Aoki takes 3 for a total of 3
- The difference is 5 - 3 = 2
Thus, the optimal strategy is simply to sort and take cards alternately.
Algorithm
- Sort the card array \(A\) in descending order
- Takahashi’s score: sum of elements at even indices (
A[0], A[2], A[4], ...) - Aoki’s score: sum of elements at odd indices (
A[1], A[3], A[5], ...) - Output their difference
Using Python’s slice notation, this can be written concisely as:
- Takahashi’s score: sum(A[::2])
- Aoki’s score: sum(A[1::2])
Complexity
- Time complexity: \(O(N \log N)\) (dominated by sorting)
- Space complexity: \(O(1)\) (constant memory excluding input)
Implementation Notes
- Sort in descending order (by score, highest first)
- Using slices
A[::2]andA[1::2]to alternately compute sums is concise and efficient - Don’t forget to read and convert the input:
list(map(int, input().split()))
## Source Code
```python
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
takahashi = sum(A[::2])
aoki = sum(A[1::2])
print(takahashi - aoki)
This editorial was generated by qwen3-coder-480b.
posted:
last update: