nyoj-动态规划-234-吃土豆-201308131021

吃土豆

时间限制: 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 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
先说一下此题的大意:在一个二维数组中保存各个土豆的重量,每次取一个土豆,它上一行与下一行均不能选择,还有它左右的两个也不能选,按照这个规则遍历整个二维数组,最后输出我们所能获得的最大土豆质量;
思路如下:
典型的递归分制与递推问题的处理,此题若用递归算法代码将更简洁,只可惜由于时间限制,它会出现超时现象,所以我们要把它转化成非递归的递推算法,但递归思想我们不得不去领悟的,故笔者将对应的递归算法代码也一起分享给大家,希望对大家有所帮助,废话不多说,我们来看这题的解决办法:
通过分析题目我们不难发现,我们可以先对每一行求对应的最大统计值,在求解过程中注意,每取一个值,与之左右相邻的两个值均不能选取,在我们求前i个数的最大统计值时,我们要先确定前i-1个数的最大统计值,仔细体会这个方程f[i]=f[i-2]+b[i]>f[i-1]?f[i-2]+b[i]:f[i-1];,下面给出具体代码:
#include<stdio.h>
/*递归分制算法, 
int max(int n,int *b){
    if(n==1)return b[n];
    if(n==2)return b[n]>b[n-1]?b[n]:b[n-1];
    return max(n-2,b)+b[n]>max(n-1,b)?max(n-2,b)+b[n]:max(n-1,b);
}*/
非递归递推算法/// 
int max(int n,int *b){
    int i,f[510];
    for(i=1;i<=n;i++)
    {
        if(i==1)f[i]=b[i];
        else if(i==2)
        f[i]=b[i]>b[i-1]?b[i]:b[i-1];
        else
        {
            f[i]=f[i-2]+b[i]>f[i-1]?f[i-2]+b[i]:f[i-1];
        }//else
    }//for
    return f[n];
}
int main()
{
    int a[510],b[510];
    int i,j,M,N;
    while(scanf("%d %d",&M,&N)!=EOF)
    {
        for(i=1;i<=M;i++)
        {
            for(j=1;j<=N;j++)
            {
                scanf("%d",&a[j]);
            }
            b[i]=max(N,a);
        }//for
        printf("%d\n",max(M,b));
    }//while 
    //system("pause");
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值