簡單dp- Apple Catching

奶牛愛吃蘋果是鮮爲人知的事實。FJ在他的田地裏有兩棵蘋果樹(編號爲1和2)。Bessie不會爬樹,所以她必須等着蘋果掉下來。然而,她必須在空中接住它們,因爲蘋果落地時碰傷了(誰也不想吃碰傷了的蘋果)。Bessie吃得很快,吃的時間可以忽略不計。 每分鐘,兩棵蘋果樹中的一棵會掉落一個蘋果。Bessie有過很多練習,只要她站在一棵有蘋果落下的樹下,就能接住一個蘋果。Bessie可以很快地在兩棵樹之間行走,時間忽略不計。她可以隨時站在一棵樹下。此外,奶牛沒有得到大量的鍛鍊,所以她不願意在樹間來回地來回行走(因此錯過了一些蘋果)。 蘋果下降T(1 < = T< = 1000)分鐘。Bessie願意來回走至多W(1 < = W< = 30)次。考慮哪棵樹每分鐘會掉落一個蘋果,確定貝西能抓到的最大數量的蘋果。貝西從樹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.

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<set>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
int dp[1009][1009];//i爲第幾秒j爲幾次走 
int v[100009]; 
int main()
{
	int t,w;
	scanf("%d%d",&t,&w);
	for(int i = 1;i <= t;++i)
	{
		scanf("%d",&v[i]);
	}
	int ans = 0;
	for(int i = 1;i <= t;++i)
	{
		for(int j = 0;j <= w;++j)
		{
			if(j == 0)
			{
				dp[i][j] = dp[i-1][j];
			}//初始化配合下面的j爲奇數且爲樹2++,和j爲偶數且樹1++ 
			else{
			dp[i][j] = max(dp[i-1][j],dp[i-1][j-1]);//有兩個方向一個爲不換方向-個換方向	
			}
			if((j&1 && v[i] == 2) || (!(j&1) && v[i] == 1))
			{
				dp[i][j]++;
			} //判斷是否會掉下蘋果 j爲奇數且爲樹2++,和j爲偶數且樹1++ 
			ans = max(ans,dp[i][j]);//可能是不用那麼多步所以找每步的最大值 
		}
	}
	printf("%d\n",ans);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章