Apple Catching (dp 动态规划)

本文介绍了一道关于动态规划的问题——如何让Bessie在有限次数的移动中捕捉到最多的苹果。通过定义状态转移方程,文章详细解释了如何使用三维DP数组解决此问题,并给出了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 2
2
1
1
2
2
1
1
Sample Output
6

题意:有两个苹果树,每一分钟都会从有其中一颗树掉落一个苹果,输出 n,m,n为n分钟,m为最多在两棵树之间有 m次跑动,下面输出每分钟是那颗苹果树上的苹果掉落的,要输出,在两颗苹果树之间 不超过m次跑动,最多能获得多少个苹果;

思路:本来想着记忆化搜索咧,本章练习动态规划,找状态转移方程,就尝试找状态转移方程;

dp数组

dp[x][y][i] 表示在x次下落时,剩余y次走动,此时在i颗树下时能获得的最大苹果数;其实这道题有固定终点和起点;

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

#define Max 1010
int dp[Max][33][3];  //dp[x][y][i] 当处于 x次下落时,剩余y次跑动,此时在 i 树下的最大获取苹果数; 
int book[Max];
int n,m;
int main()
{
	int i,j;
	while(~scanf("%d%d",&n,&m))
	{
		for(i = 1;i<=n;i++)
			scanf("%d",&book[i]);
			
		memset(dp[n+1],0,sizeof(dp[n+1])); 
		int t;
		for(i = n;i>=1;i--)
		{
			for(j = 0;j<=m;j++)
			{
				for(t = 1;t<=2;t++)
				{
					dp[i][j][t] = dp[i+1][j][t];    // i次下落,一定是从i-1次下落转移过来的,可以从i-1次下落的这颗树下转移过来,也可以从另一棵树转移过来; 
					if(j>0) dp[i][j][t] = max(dp[i][j][t],dp[i+1][j-1][3-t]);
					if(book[i]==t) dp[i][j][t]++;
				}
			}
		}
		int Ma = max(dp[1][m-1][2],dp[1][m][1]);  // 终止条件有两个;一个都不能忽略; 
		//printf("%d\n",dp[1][m][1]);
		//printf("%d\n",dp[1][m-1][2]);
		printf("%d\n",Ma);		
	}
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值