题目描述:
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
Hint
INPUT DETAILS:
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.
题目理解:
有编号为1,2的两颗苹果树,每分钟可解一个,忽略在两棵树下移动所需的时间,输入两个数,第一个数代表接下来有n行,每行代表两颗苹果树那棵苹果树会落下苹果,第二个数代表你可以在两颗树之间移动几次,问在不超过最大移动次数的前提下,最多可以接多少苹果。初始位置在第一颗苹果树下。
这道题不妨按时间来思考,一给定时刻i,转移次数已知为j, 则它只能由两个状态转移而来: 即上一时刻同一棵树或上一时刻不同的树,那么这一时刻在转移次数为j的情况下最多能接到的苹果为那两个状态的最大值再加上当前能接受到的苹果。
(注意当前能否拿到苹果只与转移次数有关)在0时刻,不管移动次数为几,接受的苹果都为0。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1005;
int dp[1005][31];//dp[i][j]表示前i分钟移动了j次所获的苹果数
int a[maxn][3];
int main()
{
int n,k,b;
while(scanf("%d%d",&n,&k)!=EOF)
{
memset(a,0,sizeof(a));
for(int i=1;i<=n;i++)
{
scanf("%d",&b);
a[i][b]=1; //第i分钟编号为b的苹果树掉下苹果
}
memset(dp,0,sizeof(dp));
dp[1][0]=a[1][1];//起始位置在第一棵树下
for(int i=1;i<=n;i++)//第几分钟
for(int j=0;j<=k;j++)//移动次数
{
dp[i][j]=dp[i-1][j]+a[i][j%2+1];//上一时刻同一棵树 //第i分钟不移动,总共移动了j次
if(j>0)
dp[i][j]=max(dp[i][j],dp[i-1][j-1]+a[i][j%2+1]); //上一时刻不同棵树//移动,总共移动了j次
}
int maxn=0;
for(int j=1;j<=k;j++)
maxn=max(maxn,dp[n][j]);
printf("%d\n",maxn);
}
return 0;
}
//代码中的j%2,因为j代表的是移动次数,所以j%2代表的是在哪颗树下,不移动时在第一颗树下,故为j%2+1,这是算出的结果就在第一颗树下