A classic DP, is the first touch of contact, tell me about my experience.
The key to doing this is to write the state transfer equation , the key is to find the amount that can be enumerated, that is, what the subscript in this DP array represents. and be unique.
Is usually the enumeration state, and the current best state is enumerated for a state.
However, different levels of the state how to transfer is not very clear, after more questions, more understanding, mutual proof it.
The state transfer equation for this problem is: dp[i][j] = max (dp[i-1][j-1],dp[i-1][j]); I represents the first minute, J means walking around J times. This equation means that the current state depends on how he decided on the last minute, in only two cases, moving around or not moving around. So take the maximum value of the previous state.
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm>using namespace Std;int t,w;int a[1005];int dp[1005][50];int Main () { scanf ("%d%d", &t,&w); for (int i=1;i<=t;i++) scanf ("%d", &a[i]); if (a[1] = = 1) { dp[1][0] = 1; DP[1][1] = 0; } if (a[1] = = 2) { dp[1][0] = 0; DP[1][1] = 1; } for (int i=2;i<=t;i++) for (int j=0;j<=w;j++) { dp[i][j] = max (dp[i-1][j-1],dp[i-1][j]); if ((a[i]-1) = = (j%2)) { dp[i][j]++; } } int MAXN =-1; for (int i=0;i<=w;i++) if (maxn<dp[t][i]) MAXN = dp[t][i]; printf ("%d\n", MAXN); return 0;}
Apple catching. (POJ-2385)