问题描述
It is a little known fact that cows love apples. Farmer John has two apple trees (which are conveniently numbered 1 and 2) in his field, each full of apples. Bessie cannot reach the apples when they are on the tree, so she must wait for them to fall. However, she must catch them in the air since the apples bruise when they hit the ground (and no one wants to eat bruised apples). Bessie is a quick eater, so an apple she does catch is eaten in just a few seconds.
Each minute, one of the two apple trees drops an apple. Bessie, having much practice, can catch an apple if she is standing under a tree from which one falls. While Bessie can walk between the two trees quickly (in much less than a minute), she can stand under only one tree at any time. Moreover, cows do not get a lot of exercise, so she is not willing to walk back and forth between the trees endlessly (and thus misses some apples).
Apples fall (one each minute) for T (1 <= T <= 1,000) minutes. Bessie is willing to walk back and forth at most W (1 <= W <= 30) times. Given which tree will drop an apple each minute, determine the maximum number of apples which Bessie can catch. Bessie starts at tree 1.
Input
* Line 1: Two space separated integers: T and W
* Lines 2..T+1: 1 or 2: the tree that will drop an apple each minute.
Output
* Line 1: The maximum number of apples Bessie can catch without walking more than W times.
Sample Input
7 2
2
1
1
2
2
1
1
Sample Output
6
动态规划,我最害怕的一个算法。这题又涉及到递推,我真的是想了半天想了半天。后来才知道这题真水,可以递推是真的需要脑子能够转出来才能理解好。
ok,我们定义dp[i][j]为时间i,走j次接到苹果的最多数目。
因为起初的状态是在树1下,所以很容易能够想到如果第一个苹果是树2先掉,那么dp[1][0] = 0,dp[1][1] = 1(因为可以走一次到树2接苹果)。
如果第一个苹果是树1掉,那么不用走直接就拿到,所以dp[1][0] = 1而dp[1][1] = 0。
其他情况:
当j=0时候,也就是说它一直在树1下接苹果,所以dp[i][0] = dp[i-1][0] + a[i]%2(当a[i]为1,即树1掉苹果,所以要加1)。
当j!=0时候,也就是说它会转换j次,它的状态是时间i-1时转换j次接到的苹果树然后站那不动等着时间i时候的情况和时间i-1时转换j-1次接到的苹果数然后再转换1次后的情况的最大值,即dp[i][j] = max(dp[i-1][j], dp[i-1][j-1])。
然而到达dp[i][j]时要判断是否接到此时间掉的树,根据j来判断。即
if(j % 2 + 1 == m[i])
dp[i][j] ++;
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1000+10;
int m[maxn];
int dp[maxn][35];//dp[i][j]定义为第i个苹果下落,走j次拿了最多的苹果数
int main()
{
int T,W;
scanf("%d%d",&T,&W);
for(int i=1; i<=T; i++)
{
scanf("%d",&m[i]);
}
if(m[1]==2)
{
dp[1][0] = 0;
dp[1][1] = 1;
}
else
{
dp[1][0] = 1;
dp[1][1] = 0;
}
for(int i=2; i<=T; i++)
{
for(int j=0; j<=W; j++)
{
if(j==0)
{
dp[i][j] = dp[i-1][j] + m[i]%2;
continue;
}
else
dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]);
if(j % 2 + 1 == m[i])
dp[i][j] ++;
}
}
// for(int j=0; j<=W; j++)
// {
// for(int i=1; i<=T; i++)
// printf("%d ",dp[i][j]);
// printf("\n");
// }
printf("%d\n",dp[T][W]);
return 0;
}