吃土豆

来源:互联网 发布:瑞芯微电子 知乎 编辑:程序博客网 时间:2024/06/02 20:37

吃土豆

时间限制:1000 ms  |  内存限制:65535 KB
难度:4
描述
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<=500.
输出
For each case, you just output the MAX qualities you can eat and then get.
样例输入
4 611 0 7 5 13 978 4 81 6 22 41 40 9 34 16 1011 22 0 33 39 6
样例输出
242

思路:

两层动归, 横向和纵向, 横向的可以求出每一行的最大值(将二维变成一维), 纵向可利用横向dp的结果, 求出最终的结果。转移方程:map[i][j] += max(map[i][j-2], map[i][j-3])(选取j列, 则前面可转移而来的只有j-2或j-3列);dp[i] += max(dp[i-2] , dp[i-3])(同列转移方程)。

#include <stdio.h>#include <string.h>#include <stdlib.h>int map[501][501], dp[501];     //map[i][j]:在i行:col坐标从0到j能取到的最大qualities。dp[i]:到i列(取i)的最大qualitiesint max(int a, int b){return a > b ? a : b;}int main(){int n, m, i, j;while(scanf("%d%d", &n, &m) != EOF){memset(map, 0, sizeof(map));memset(dp, 0, sizeof(dp));for(i = 0; i < n; i++)                     //在进行输入的同时进行col的dp{for(j = 0; j < m; j++){scanf("%d", &map[i][j]);if(j == 2){map[i][j] += max(map[i][j-2], 0);}else if(j > 2){map[i][j] += max(map[i][j-3], map[i][j-2]);}}dp[i] = max(map[i][m-1], map[i][m-2]);}dp[2] += max(dp[0], 0);for(i = 3; i < n; i++)                     //进行row的dp{dp[i] += max(dp[i-2], dp[i-3]);}printf("%d\n", max(dp[n-1], dp[n-2]));}return 0;}


0 0
原创粉丝点击