poj2385 Apple Catching(动态规划)

题目链接:http://poj.org/problem?id=2385

题目大意:fj有两颗长满苹果的苹果树,奶牛够不着树上的苹果,只能等苹果落地,苹果一旦落在地上即不能吃了,只有在下落的时候可以接住吃掉,奶牛一次只能站在一颗树下,但可以在两棵树间互相移动,但最多移动W次。会落下T个苹果。初始时奶牛在树1下面,但可以迅速移动到树2下面。

动态规划的策略是:dp[i][j]的值为第i个苹果掉落时奶牛移动了j次,此时吃掉的最多苹果数。

dp[i][j] = max(dp[i-1][j],dp[i-1][j-1]) + 当前苹果是否能吃掉

即当前能吃的最多苹果数肯定是从上一个苹果的状态不移动过来,或从上一个苹果的状态移动一步过来。

再加上当前这个苹果能否吃掉 1或者0  即是当前的状态了。

边缘处理是dp[i][0] = dp[i-1][0] + 当前苹果能否吃掉

j = 0 即没有移动过,即一直在树1下面。

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.

 

下面是已AC的代码

#include <iostream>
#include <cstdio>
using namespace std;

int dp[1005][35]; // dp[i][j] 第i个苹果掉落时移动了j次的苹果数
int a[1005];

int main()
{
        int T, W;
        scanf( "%d%d", &T, &W );
        for ( int i = 1 ; i <= T ; ++ i ) {
                scanf( "%d", &a[i] );
        }
        for ( int i = 1 ; i <= T ; ++ i ) {
                // 移动0次 一定是没有移动 在树1下面
                dp[i][0] = dp[i-1][0] + 2-a[i];
                for ( int j = 1 ; j <= W ; ++ j ) {
                        if ( j % 2 ) // 树2下面
                                // 则由上一分钟的原地不动dp[i-1][j]
                                // 或者上一分钟到这一分钟移动一步的dp[i-1][j-1] 过来
                                // 然后看当前苹果是在2下面 还是1下面
                                dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]) + a[i]-1;
                        else
                                dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]) + 2-a[i];
                }
        }

        int res = 0;
        for ( int i = 1 ; i <= W ; ++ i ) {
                if ( res < dp[T][i] ) res = dp[T][i];
        }
        printf("%d\n", res);

        return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值