nyoj-动态规划-234-吃土豆-201308131021
2013-08-13 15:13
288 查看
吃土豆
时间限制: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 ; if(n==2)return b >b[n-1]?b :b[n-1]; return max(n-2,b)+b >max(n-1,b)?max(n-2,b)+b :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 ; } 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; }
[/code]
相关文章推荐
- 吃土豆_nyoj_234(动态规划).java
- hdu-Beans(动态规划,nyoj-234-吃土豆)
- NYOJ234吃土豆(双层动态规划)
- nyoj-234-吃土豆(动态规划)
- NY--234 -- 吃土豆 [二维动态规划]
- NYOJ234吃土豆
- nyoj234 吃土豆 01背包
- NYOJ 234 吃土豆
- nyoj 234 吃土豆
- NYOJ234-吃土豆(双层DP)
- NYOJ 234 吃土豆(基础dp)
- nyoj 234 吃土豆
- nyoj 234 吃土豆
- NYOJ-234 吃土豆
- NYOJ 吃土豆(动态规划)
- Nyoj 234 吃土豆
- NYOJ 234 吃土豆
- NYOJ_234_吃土豆
- nyoj 吃土豆 234 (双层DP)
- NYOJ 题目234 吃土豆