SDUT_2015寒假集训_动规递推_E-Apple Catching

来源:互联网 发布:手机测光软件 编辑:程序博客网 时间:2024/06/02 16:48

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.


一道不是很难的动规题,不过一开始自己想了半天没想出什么来。(果然我还差得远呢QAQ)研究了几个大神的题解后,学了一种适合自己思维的方法。建立一个二维数组a[i][j]来统计第i分钟走了j次后最多能得多少个苹果。因为只有两棵树,所以我们可以用j%2+1来判断走了j次后Bessie呆在哪棵树下。可以推出,当第i分钟第j次Bessie得到了苹果时,此时得到最大苹果数a[i][j]=max(a[i-1][j-1],a[i-1][j]+1);,没得到苹果时所得的最大苹果数a[i][j]=max(a[i-1][j-1],a[i-1][j]);,还有Bessie第i分钟没有动的情况,拿出来单独考虑。代码如下。

代码

#include <iostream>using namespace std;int main(){    int t,w,i,j,k,a[1100][35],app[1100];    cin>>t>>w;    for(i=1;i<=t;i++)        cin>>app[i];    for(i=1;i<=t;i++)    {        a[i][0]=a[i-1][0]+(app[i]==1);        for(j=1;j<=w&&j<=i;j++)        {            if(app[i]==j%2+1)            a[i][j]=max(a[i-1][j-1]+1,a[i-1][j]+1);            else            a[i][j]=max(a[i-1][j-1],a[i-1][j]);        }    }    k=a[t][1];    for(i=2;i<=w;i++)    {        if(a[t][i]>k)        k=a[t][i];    }    cout<<k<<endl;    return 0;}


0 0
原创粉丝点击