可以用dp,但有两个dp数组,而且是三维的,原谅我dp知识的匮乏。。
以后补上更具体说明
#include<stdio.h>
#include<string.h>
int maxs(int x, int y)
{
if (x > y)
return x;
else
return y;
}
int main()
{
int dp[1002][32][2];
int tree[1002];
int mint, step, max;
while (scanf("%d%d",&mint,&step) != EOF)
{
memset(dp, 0, sizeof(dp));
max = -1;
for (int i = 1; i <= mint;++i)
{
scanf("%d", &tree[i]);
}
for (int i = 1; i <= mint; ++i)
{
for (int j = 0; j <=step; --j)
{
if (tree[i] == 1)
{
dp[i][j][0] = dp[i-1][j][0] + 1;
if (j <step)
{
dp[i][j][0] = maxs(dp[i][j][0], dp[i - 1][j+1][1] + 1);
}
dp[i][j][1] = dp[i-1][j][1];
if (j <step)
{
dp[i][j][1] = maxs(dp[i][j][1], dp[i - 1][j+1][0]);
}
max = maxs(dp[i][j][0], max);
max = maxs(dp[i][j][1], max);
}
else
{
dp[i][j][1] = dp[i - 1][j][1] + 1;
if (j <step)
{
dp[i][j][1] = maxs(dp[i][j][1], dp[i - 1][j+1][0] + 1);
}
dp[i][j][0] = dp[i - 1][j][0];
if (j <step)
{
dp[i][j][0] = maxs(dp[i][j][0], dp[i - 1][j+1][1]);
}
max = maxs(dp[i][j][0], max);
max = maxs(dp[i][j][1], max);
}
}
}
printf("%d\n", max);
}
return 0;
}