Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11546 | Accepted: 5565 |
Description
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
* Lines 2..T+1: 1 or 2: the tree that will drop an apple each minute.
Output
Sample Input
7 2 2 1 1 2 2 1 1
Sample Output
6
Hint
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.
Source
也是一個很簡單的遞歸題,我這裏設置了三個參量,其實第三個可以用第二個表示的,但是爲了方便犧牲一點空間其實也沒啥...
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int dp[1005][3][35],t,w,ap[1005],ma;
while(cin>>t>>w)
{
memset(dp,-0x3f3f3f,sizeof(dp));
for(int i=1;i<=t;i++)
cin>>ap[i];
if(ap[1]==1)
{
dp[1][1][0]=1;
dp[1][2][1]=0;
}
else
{
dp[1][1][0]=0;
dp[1][2][1]=1;
}
for(int i=2;i<=t;i++)
{
if(ap[i]==1)
{
for(int j=0;j<=w;j++)
{
dp[i][1][j]=max(dp[i][1][j],dp[i-1][1][j]+1);
dp[i][2][j+1]=max(dp[i][2][j+1],dp[i-1][1][j]);
dp[i][1][j+1]=max(dp[i][1][j+1],dp[i-1][2][j]+1);
dp[i][2][j]=max(dp[i][2][j],dp[i-1][2][j]);
}
}
else
{
for(int j=0;j<=w;j++)
{
dp[i][1][j]=max(dp[i][1][j],dp[i-1][1][j]);
dp[i][1][j+1]=max(dp[i][1][j+1],dp[i-1][2][j]);
dp[i][2][j]=max(dp[i][2][j],dp[i-1][2][j]+1);
dp[i][2][j+1]=max(dp[i][2][j+1],dp[i-1][1][j]+1);
}
}
}
ma=0;
for(int i=0;i<=w;i++)
{
if(dp[t][1][i]>ma)
ma=dp[t][1][i];
if(dp[t][2][i]>ma)
ma=dp[t][2][i];
}
cout<<ma<<endl;
}
return 0;
}