The main topic: there are two apple trees, numbered 1, 2, every minute a tree will drop an apple. A cow under the tree to pick apples, only to stand under a tree every minute, but the time between the transfer of trees is negligible. Given the maximum number of transfers W, ask this cow how many apples can be caught?
Analysis: The problem is solved with dynamic programming, the key question is what is the state?
Think of time, a given moment I, the number of transfers known as J, then it can only be transferred from two states.
The same tree or a different tree at the last moment.
At this point, the maximum number of apples that can be received at the time of the transfer is J plus the apples that are currently available to the two states. (Note that the current availability of apples is only related to the number of transfers)
That
1 dp[i][j] = max (dp[i-1][j], dp[i-1][j-1]); 2 if (j%2+1 = = i) {3 dp[i][j]++; 4 }
In 0 hours, regardless of the number of moves, the accepted apples are 0
The subject code is as follows
1 /*Dp[t][w]2 3 DP[0][0..W] = 0;4 dp[i][0] = dp[i-1][0];5 Dp[i][j] = max (Dp[i-1][j], dp[i-1][j-1]);6 if (j%2+1 = = i) {7 dp[i][j]++;8 }*/9#include <cstdio>Ten#include <cstring> One#include <iostream> A using namespacestd; - intdp[1002][ *]; - intapple[1002]; the - intMainintargcChar Const*argv[]) - { - intT, W; +scanf"%d%d",&t,&W); - for(inti =1; I <= t; i++) { +scanf"%d",&apple[i]); A } atMemset (DP,0,sizeof(DP)); - for(inti =1; I <= t; i++) { - for(intj =0; J <= W; J + +) { - if(J = =0) { -DP[I][J] = dp[i-1][j]; - } in Else { -DP[I][J] = max (dp[i-1][J], dp[i-1][j-1]); to } + if(j%2+1==Apple[i]) { -dp[i][j]++; the } * } $ }Panax Notoginseng intAns = dp[t][0]; - for(intj =1; J <= W; J + +) { the if(Ans <Dp[t][j]) { +Ans =Dp[t][j]; A } the } +printf"%d\n", ans); - $ $ return 0; -}
Dynamic planning is really not easy!
POJ 2385 Apple Catching