POJ 2385 Apple Catching(简单DP)

Apple Catching

Time Limit: 1000MS


Memory Limit: 65536K

Total Submissions: 9789


Accepted: 4762

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 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.


题意:有两棵树,每一分钟其中一棵树都会掉下来一个苹果,奶牛从一棵树下移动到另一棵树下的时间远小于一分钟,可以视作瞬移。现在给出T分钟内每颗苹果下落的情况(从哪个树下落),及奶牛允许瞬移的次数。问最多能接到多少个苹果?

简单DP,我特么都不会(捂脸哭/(ㄒoㄒ)/~~)。有神说推不出递推关系就写记忆化搜索。靠!记忆化搜索半天也没写出来。抓了一发题解,看懂了。

代码和解释如下:(Attention:just one test case )
//对在第一颗树和在第二颗树下分别用2-a[i],a[i]-1来记录当前树是否有苹果落下
//避免判断,很机智的方法啊,○| ̄|_ 
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std; 
int a[1010];
int dp[1010][35];//表示第i分钟移动j次能接到的最大苹果数量 
int main()
{
	int n,w,i,ans,j;
	scanf("%d%d",&n,&w);
	for(i=1;i<=n;++i)
		scanf("%d",&a[i]);
	memset(dp,0,sizeof(dp));
	for(i=1;i<=n;++i)
	{
		dp[i][0]=dp[i-1][0]+2-a[i];//移动0次,始终在第一颗树下 
		for(j=1;j<=w;++j)
		{
			if(j&1)//当j为奇数时,奶牛在第二棵树下,否则在第一棵树下
		//当前位置是上一分钟后从另一棵树下移动过来的,或者上一分钟也在这个位置 
				dp[i][j]=max(dp[i-1][j-1],dp[i-1][j])+a[i]-1;
			else
				dp[i][j]=max(dp[i-1][j-1],dp[i-1][j])+2-a[i];
		}
	}
	ans=0;
	for(i=0;i<=w;++i)
		ans=max(dp[n][i],ans);
	printf("%d\n",ans);
	return 0;
}









你可能感兴趣的:(POJ 2385 Apple Catching(简单DP))