Beans
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2873 Accepted Submission(s): 1392
Problem Description
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 ?

Now, how much qualities can you eat and then get ?
Input
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.
Output
For each case, you just output the MAX qualities you can eat and then get.
Sample Input
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
Sample Output
242
Source
解题思路:列的状态只与最多之前三列的选择有关系,滚动数组搞一下求出单的最优值,行的状态与列状态相同,也用滚动数组搞一下,更新答案即可
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int **matrix;
int main()
{
int m,n,i,j,r[4],c[4],temp,ans;
while(scanf("%d%d",&m,&n)!=-1)
{
ans=-1;
matrix=new int*[m+1];
for(i=0;i<=m;i++)
matrix[i]=new int[n+1];
memset(r,0,sizeof(r));
memset(c,0,sizeof(c));
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&matrix[i][j]);
for(i=1;i<=m;i++)
{
c[1]=matrix[i][1];
c[2]=max(matrix[i][1],matrix[i][2]);
c[3]=max(matrix[i][1]+matrix[i][3],matrix[i][2]);
temp=max(max(c[1],c[2]),c[3]);
for(j=4;j<=n;j++)
{
c[j%4]=max(max(c[(j-2)%4]+matrix[i][j],c[(j-3)%4]+matrix[i][j]),c[(j-1)%4]);
if(temp<c[j%4])
temp=c[j%4];
}
if(i==1)
r[i%4]=temp;
else if(i==2)
r[i%4]=max(temp,r[1]);
else if(i==3)
r[i%4]=max(r[1]+temp,r[2]);
else
r[i%4]=max(max(r[(i-2)%4]+temp,r[(i-3)%4]+temp),r[(i-1)%4]);
}
for(i=0;i<4;i++)
if(ans<r[i])
ans=r[i];
printf("%d\n",ans);
}
delete matrix;
return 0;
}