/*http://acm.hdu.edu.cn/diy/diy_previewproblem.php?cid=19572&pid=1018
Beans
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 2 Accepted Submission(s) : 1
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
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 ?
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
2009 Multi-University Training Contest 4 - Host by HDU
解析:这道题目一开始看的时候想复杂了。其实归根究底就是求最大和问题,而这个和有点曲折罢了,需要考虑相间条件。
1.首先优化每行,对每一行可以看做一个数列,第i行,即这个的数列相间的和的最大值保存成r[i]
2.然后同理求得数列r 的最大值即可
3.状态转移方程:f[i]=max(f[i-1],f[i-2]+a[i]);//选择相间隔的数,要么选择前一个舍弃当前的,要么选择当前=f[i-2]+a[i]
4.注意这里的间隔条件
*/
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn=200000+5;
int f[maxn];
int r[maxn];
int b[maxn];
int max(int x,int y)
{
return x>y? x:y;
}
int findmax(int a[],int n)
{
memset(f,0,sizeof(f));
int ans,i;
f[1]=a[1];
for(i=2;i<=n;i++)
f[i]=max(f[i-1],f[i-2]+a[i]);//选择相间隔的数,要么选择前一个舍弃当前的,要么选择当前=f[i-2]+a[i]
return f[n];
}
int main()
{
int n,m,i,j;
int ans,t;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)//对于每行取间隔数进行优化
{scanf("%d",&b[j]);
}
r[i]=findmax(b,m);
}
ans=findmax(r,n); //在优化后每行最大值组成一组元素,再从中选出相间的数
printf("%d\n",ans);
}
return 0;
}