Блог пользователя your.nemesis

Автор your.nemesis, история, 5 лет назад, По-английски

I have had this doubt in dynamic programming for a long time now regarding which states to use. The question goes something like this:

Reading Input:

Recursion Code: So from the basic intuition I wrote this code. Which is obviously MLE:

Then I tried this code:

And this code passed the test cases and got AC. So now coming back to my doubt. There have been many problems where

$$$ dp[i][j][k] -- \gt $$$ is optimized to $$$-- \gt dp[i][j] $$$ because the state j is always changing. But I have also practiced questions where trying this $$$ dp[i][j][k] -- \gt $$$ is optimized to this --> $$$ dp[i][j] $$$ and it got me a WA.

So can someone please explain when to take a state into consideration so that I dont fall into this MLE trap again in the near future?

Thank you:)

  • Проголосовать: нравится
  • -1
  • Проголосовать: не нравится

»
5 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

In your case, MLE was caused because you were allotting too much memory (5000*5000*5000*sizeof(int) bytes). In some other cases, MLE can be caused due to overflow during recursion (while performing recursive dp, probably).
But coming to states of a dp problem, it is a technique which can only be mastered by practice and practice only. There is no shortcut route in instantly understanding what should be the states for a particular dp problem. In general, you can sort of get an idea about the states from the constraints (say for a problem, where $$$N,M \le 2e5$$$, the intended solution obviously isn't $$$dp[N][M]$$$). This is something you can understand better by practising more and more problems on dp.

»
5 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Any link for this problem

»
5 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

I think your second code should have WA'd. Maybe you were lucky or can anyone convince me otherwise? To save memory in this case, it is enough to solve the problem in tabular style and use dp[2][a][b] then rollover dp values to represent the states as the transition only requires the previous dp array.