Editorial
Call a position losing if the second player wins from it. Let be the number of piles with an odd size, and let be the minimum pile size.
The only possible values of are , , and . We handle the special case , separately.
Case
Every move decreases the total number of stones by exactly one, so the game always lasts moves. The position is losing exactly when this sum is even.
Case
A position is losing exactly when all piles are even. Any move from such a position creates at least one odd pile. Conversely, if an odd pile exists, choose all odd piles to make every pile even.
Case
A position is losing exactly when all pile sizes have the same parity. From an all-even or all-odd position, choosing between one and piles makes the parities mixed. Conversely, from a mixed position, choose every odd pile to make all piles even.
Case
Here . Exactly the following positions are losing.
- Every pile is even.
- Exactly piles are odd, and the unique even pile has the minimum size.
From the first type, a move creates between one and odd piles, so neither losing type can be reached.
From the second type, making every pile even would require choosing all odd piles, which is impossible. To reach another position of the second type, the unique even pile and exactly one odd pile would have to be chosen. The old minimum then decreases by one and becomes odd, making it smaller than the new unique even pile. Thus, the new even pile is not a minimum. No move goes from a losing position to another losing position.
It remains to show that every other position can reach a losing position.
- If there are between one and odd piles, choose all odd piles to make every pile even.
- If all piles are odd, choose one minimum pile. It becomes the unique even pile and remains a minimum.
- If exactly piles are odd but the unique even pile is not a minimum, choose that even pile and a minimum odd pile. The latter becomes the unique even pile and the minimum.
Therefore, it is enough to compute , , and the total number of stones for each test case. The time complexity is , and the additional space complexity is .
Solution written by GPT6