Description
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
* Lines 2..T+1: 1 or 2: the tree that will drop an apple each minute.
Output
Sample Input
7 2 2 1 1 2 2 1 1
Sample Output
6
Hint
Seven apples fall - one from tree 2, then two in a row from tree 1, then two in a row from tree 2, then two in a row from tree 1. Bessie is willing to walk from one tree to the other twice.
OUTPUT DETAILS:
Bessie can catch six apples by staying under tree 1 until the first two have dropped, then moving to tree 2 for the next two, then returning back to tree 1 for the final two.
用opt[i][j]表示第i分钟走了j次后最多能摘几个苹果
由于只有两棵树,故用j%2+1就能判断此时Bessie在哪棵树下面,省下了一维空间
f[i]表示第i分钟哪颗树掉苹果,若f[i]==j%2+1,则此时可以摘得苹果,opt[i][j]=max(opt[i-1][j],opt[i-1][j-1])+1
否则,此时摘不到苹果,opt[i][j]==max(opt[i-1][j],opt[i-1][j-1])
但对于opt[i][0]要单独考虑,即第i分钟时仍然没移动,在第一棵树下的情况,可由opt[i-1][0]推导
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int dp[1001][31],f[1001];
int main()
{
int t,w;
while(~scanf("%d %d",&t,&w))
{
for(int i=1;i<=t;i++) scanf("%d",&f[i]);
memset(dp,0,sizeof(dp));
for(int i=1;i<=t;i++){
dp[i][0]=dp[i-1][0];
if(f[i]==1)
dp[i][0]++;
for(int j=1;j<=w&&j<=i;j++){
if(j%2+1==f[i]){
dp[i][j]=max(dp[i-1][j],dp[i-1][j-1])+1;
}
else
dp[i][j]=max(dp[i-1][j],dp[i-1][j-1]);
}
}
int k=dp[t][0];
for(int i=1;i<=w;i++)
k=max(k,dp[t][i]);
printf("%d\n",k);
}
return 0;
}
328



被折叠的 条评论
为什么被折叠?



