2014
02-17

# Beans

Bean-eating is an interesting game, everyone owns an M*N matrix, which is filled with different qualities beans. Meantime, there is only one bean in any 1*1 grid. Now you want to eat the beans and collect the qualities, but everyone must obey by the following rules: if you eat the bean at the coordinate(x, y), you can’t eat the beans anyway at the coordinates listed (if exiting): (x, y-1), (x, y+1), and the both rows whose abscissas are x-1 and x+1.

Now, how much qualities can you eat and then get ?

There are a few cases. In each case, there are two integer M (row number) and N (column number). The next M lines each contain N integers, representing the qualities of the beans. We can make sure that the quality of bean isn’t beyond 1000, and 1<=M*N<=200000.

There are a few cases. In each case, there are two integer M (row number) and N (column number). The next M lines each contain N integers, representing the qualities of the beans. We can make sure that the quality of bean isn’t beyond 1000, and 1<=M*N<=200000.

4 6
11 0 7 5 13 9
78 4 81 6 22 4
1 40 9 34 16 10
11 22 0 33 39 6

242

#include<stdio.h>
#include<string.h>
int n,m;
int a[200005],dp[200005][2],b[200005];
int max(int x,int y)
{
return x>y?x:y;
}
int main()
{
int i,j,res;
while(scanf("%d%d",&n,&m)!=EOF)
{
res=-1000000;
dp[0][0]=0;dp[0][1]=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d",&a[j]);
dp[j][0]=max(dp[j-1][0],dp[j-1][1]);
dp[j][1]=dp[j-1][0]+a[j];
}
b[i]=max(dp[m][0],dp[m][1]);
if(res<b[i])
res=b[i];
}
dp[0][0]=0;dp[0][1]=0;
for(i=1;i<=n;i++)
{
dp[i][0]=max(dp[i-1][0],dp[i-1][1]);
dp[i][1]=dp[i-1][0]+b[i];
if(res<dp[i][0])
res=dp[i][0];
if(res<dp[i][1])
res=dp[i][1];
}
printf("%d\n",res);
}
return 0;
}

1. 给你一组数据吧：29 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 1000。此时的数据量还是很小的，耗时却不短。这种方法确实可以，当然或许还有其他的优化方案，但是优化只能针对某些数据，不太可能在所有情况下都能在可接受的时间内求解出答案。