Official

D - Stones Editorial by en_translator


Intended wrong answer

You cannot solve this problem with a greedy approach of “remove as many stones as they can in each turn.” The counterexample is:

10 3
1 3 4
Let us check that this is indeed the counterexample of the greedy algorithm. If Takahashi uses greedy approach, an example of the progression of the game is as follows. (Here, Takahashi greedily remove stones, but Aoki doesn’t, so this is merely an example)

  • Takahashi removes 44 stones.
  • Aoki removes 44 stones.
  • Takahashi removes 11 stones.
  • Aoki removes 11 stones.

In this example, Takahashi is forced to remove 55 stones due to Aoki’s move. However, if Takahashi removes 33 stones, no matter how many stones Aoki remove in the next turn, Takahashi can remove 33 or more stones in the next turn, so he can remove at least 66 stones.

Thus, depending on {Ai}\{A_i\} and NN, this problem may require a complex strategy. Therefore, we came up with using exhaustive-search algorithm.

Intended answer

This problem can be solved with the following DP (Dynamic Programming):

DP[n]=\mathrm{DP}[n]= the number of stones that the first player can take if the game starts with a pile with nn stones.

The transition is:

DP[n]=max{Ai+(nAi)DP[nAi]Ain}.\mathrm{DP}[n]=\max \{A_i+(n-A_i)-\mathrm{DP}[n-A_i] \mid A_i\leq n\}.

The semantics of this equation is: if the first player removes AiA_i stones, he will end up with removing Ai+A_i+ (the number of stones that the second player can remove if the game starts with a pile with nAin-A_i) stones, so the desired value is the maximum over all ii.

This DP has O(N)O(N) states, each transition of which is processed in an O(K)O(K) time, so we can find DP[N]\mathrm{DP}[N] in a total of O(NK)O(NK) time.

Sample code (C)

posted:
last update:



2025-04-08 (Tue)
17:56:40 +00:00