吃土豆

来源:互联网 发布:情定三生向天和知夏 编辑:程序博客网 时间:2024/04/27 19:49

吃土豆

时间限制: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
题意 吃豆子游戏 当你吃了一个格子的豆子 该格子左右两个和上下两行就不能吃了 输入每个格子的豆子数 求你最多能吃多少颗豆子

可以先求出每行你最多可以吃多少颗豆子 然后每行就压缩成只有一个格子了 里面的豆子数就是那一行最多可以吃的豆子数 然后问题就变成求一列最多可以吃多少颗豆子了 和处理每一行一样处理 那么问题就简化成求一行数字的最大不连续和问题了

令row[i]表示某一行前i个豆子的最大和 有两种情况 吃第i个格子中的豆子和不吃第i个格子中的豆子 a[i]为第i个格子中的豆子数

吃 row[i]=row[i-2]+a[i] 不吃 row[i]=row[i-1]所以有转移方程 row[i]=max(row[i-2]+a[i],row[i-1])

#include<stdio.h>#include<string.h>#include<iostream>using namespace std;int a[1000][1000];int row[1000],dp[1000];int we[1000];int main(){    int n,m;    while(scanf("%d%d",&n,&m)!=-1)    {        memset(dp,0,sizeof(dp));        memset(row,0,sizeof(row));        memset(we,0,sizeof(we));        for(int i=0;i<n;i++)        {            for(int j=0;j<m;j++)            {                scanf("%d",&a[i][j]);            }        }        for(int i=0;i<n;i++)        {           for(int j=0;j<m;j++)           {               row[j]=max(row[j-1],row[j-2]+a[i][j]);           }           dp[i]=row[m-1];        }        for(int i=0;i<n;i++)        {            we[i]=max(we[i-1],we[i-2]+dp[i]);        }        printf("%d\n",we[n-1]);    }}

0 0
原创粉丝点击