描述
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 ?
-
输入
-
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<=500.
输出
- For each case, you just output the MAX qualities you can eat and then get. 样例输入
-
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
由题易知在某一行选择一个后其上一行与下一行就无法选择且选中的左右也无法别选择,又易知若在该行选必然要让在该行的值最大,则每一行都会得到一个值再用相同的规则选择,则可将二维降为一维;
递推式:
x=0 f(x)=qu[x],x=1 f(x)=max(qu[0],qu[1]);
x>=2 f(x)=max(f(x-2)+qu[x],f(x-1));
#include<stdio.h> #define max(a,b) ((a)>(b))?(a):(b) int dp[500]; int qu[500]; int main() { int n,m; while(~scanf("%d %d",&n,&m)) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(j==0) scanf("%d",&dp[j]); else { scanf("%d",&dp[j]); if(j==1) dp[j]=max(dp[j],dp[j-1]); else dp[j]=max(dp[j-2]+dp[j],dp[j-1]); } } qu[i]=dp[m-1]; } dp[0]=qu[0];dp[1]=max(qu[0],qu[1]); for(int i=2;i<n;i++) dp[i]=max(dp[i-2]+qu[i],dp[i-1]); printf("%d\n",dp[n-1]); } return 0; }