POJ 2385 Apple Catching

来源:互联网 发布:数据还原 编辑:程序博客网 时间:2024/05/16 17:56

Description

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 22112211

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树下,奶牛每分钟只能选择移动或不移动,现按序给定苹果下落的树号,求解奶牛最多得到的苹果数。

此题动态规划求解,dp[i][j]表示第i分钟移动j次所接到的苹果最大数,则不难得到转移方程dp[i][j]=max{dp[i-1][j],dp[i-1][j-1]},边界是dp[i][j]  j==0时,所得到的苹果为i分钟内1树的苹果数,若第一分钟苹果出现在1树上,则dp[1][0]为1,dp[1][1]为0;若第一分钟苹果出现在2树上,则dp[1][0]为0,dp[1][1]为1,最后找到t分钟时w步以内的最大值就可以看,也就是max{dp[t][0],dp[t][1]...dp[t][w-1]},代码如下:



#include <iostream>using namespace std;int dp[1010][32];//dp[i][j]表示第i分钟移动j步可得的最大苹果数int main(){ios::sync_with_stdio(false);int app[1010];int t,w;cin>>t>>w;for(int i=1;i<=t;i++)cin>>app[i];dp[1][0]=app[1]==1?1:0;//如果第一个苹果出现在第一棵树上,则第1分钟移动0步可得1个苹果dp[1][1]=app[1]==2?1:0;//如果第一个苹果出现在第二棵树上,则第1分钟移动1步可得1个苹果for(int i=2;i<=t;i++)for(int j=0;j<=w;j++){if(j==0)dp[i][j]=dp[i-1][j]+(app[i]==1?1:0);//若未移动,则苹果数为上一分钟苹果数加这一分钟1树的苹果else{dp[i][j]=max(dp[i-1][j],dp[i-1][j-1]);//转移方程if(app[i]==j%2+1)dp[i][j]++;}}int maxn=-2000;for(int i=0;i<=w;i++)//找出t分钟移动i步以内获得的最大苹果数maxn=max(maxn,dp[t][i]);cout<<maxn<<endl;return 0;}



0 0
原创粉丝点击