poj Apple Catching 2385 (DP&&技巧转换)

来源:互联网 发布:淘宝耐克旗舰店是真的 编辑:程序博客网 时间:2024/06/05 04:51
Apple Catching
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 9823 Accepted: 4773

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.
//题意:
有两棵苹果树,一头牛很喜欢吃苹果,但它又特别懒,刚开始时这头牛在第一棵树下。
现在给你t分钟内苹果下落情况(第i秒从哪棵树上掉下),并且告诉你这头牛最多在
这两棵树下折返的次数(很懒)。问这头牛最多能吃多上苹果。
//思路:
一个明显的DP,用一个二维数组dp[i][j]来表示在前i秒内这头牛折返了j次。
并且用2-a[i],表示牛在第一棵树下每秒吃的苹果树(也就是1个);
 用a[i]-1表示牛在第二棵树下每秒吃的苹果数。
有了这个转化就容易了。那么dp[i][j]的值为可以表示为
当牛移动了奇数次时,牛在第二棵树下
 dp[i][j]=max(dp[i-1][j-1],dp[i-1][j])+2-a[i];
当牛移动了偶数次时,牛在第一棵树下
  dp[i][j]=max(dp[i-1][j-1],dp[i-1][j])+a[i]-1;
最后再找出在t秒内移动了i(1<=i<=w)次中最多的苹果数
 
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int a[1010];int dp[1010][35];int main(){int t,w;int i,j;while(scanf("%d%d",&t,&w)!=EOF){for(i=1;i<=t;i++)scanf("%d",&a[i]);memset(dp,0,sizeof(dp));for(i=1;i<=t;i++){dp[i][0]=dp[i-1][0]+2-a[i];for(j=1;j<=w;j++){if(j&1)dp[i][j]=max(dp[i-1][j],dp[i-1][j-1])+a[i]-1;elsedp[i][j]=max(dp[i-1][j],dp[i-1][j-1])+2-a[i];}}int ans=0;for(i=1;i<=w;i++)ans=max(ans,dp[t][i]);printf("%d\n",ans);}return 0;}

0 0