poj2358(递推 + dp)

题意:2棵苹果树在 T(1 <= T <= 1,000) 分钟内随机由某一棵苹果树掉下一个苹果,奶牛站在树1或者树2下等着接苹果(接到的苹果被牛吃了,牛不吃掉在地上的苹果),它最多愿意移动W(1 <= W <= 30)次(从一颗树移动到另一棵树),问它最多能吃到多少个苹果。默认奶牛开始在第一颗树下。

Sample Input

7 2
2
1
1
2
2
1
1

第一列输入的分别是T、W,接下来的n列表示第 i 秒树(1或2)将掉下苹果。

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.

思路
由题意可以定义dp[i][j]:在第 i 秒时,移动 j 次牛接到的最大的苹果数量。
因为牛一开始在树1下,所以可以得到如下的对应关系:

Paste_Image.png

由图可以得到规律:当移动次数与牛所在的树的奇偶性不同时,牛可以接到这棵树这时掉下的苹果。

状态转移方程:
j = 0 时:dp[i][0] = dp[i - 1][0] + (arr[i] & 1);//没有移动说明一直在树1下。
j != 0) 时:dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1]) + ( (j & 1) != (arr[i] & 1) );

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int MAX_N = 1000 + 5;
int arr[MAX_N];
int dp[MAX_N][35];

void solve(int t, int w) {
    memset(dp, 0, sizeof(dp));
    for (int i = 1; i <= t; ++i)
        for (int j = 0; j <= min(i, w); ++j) {
            if (j == 0) dp[i][j] = dp[i - 1][j] + (arr[i] & 1);
            else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1]) + ((j & 1) != (arr[i] & 1));
        }
                
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int t, w;
    while (cin >> t >> w) {
        for (int i = 1; i <= t; ++i)
            cin >> arr[i];
        solve(t, w);
        cout << dp[t][w] << endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值