码迷,mamicode.com
首页 > 其他好文 > 详细

NYOJ 吃土豆(动态规划)

时间:2016-05-08 01:18:31      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

描述
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


如果是一行的话,就是说当n==1时,dp[i]表示从开始到第i个数所能取得的最大和,则有dp[i]=max(dp[i-1], dp[i-2]+a[i]);这是每一行的情况,算出每一行的所能得到的最大和,接下来再竖着来,相邻的行不能取,就能用同样的方法求出整个矩阵的最大和,总体思路就是先算每一行再将二维化成一维。


AC代码:


# include <cstdio>
# include <cstring>
# include <algorithm>
using namespace std;
int a[510][510], dp_y[510][510], ans[510];
int main(){
	int n, m, i, j, k;
	while(scanf("%d%d", &n, &m)!=EOF){
		memset(a, 0, sizeof(a));
		for(i=1; i<=n; i++){
			for(j=1; j<=m; j++){
				scanf("%d", &a[i][j]);
			}
		}
		memset(dp_y, 0, sizeof(dp_y));
		for(i=1; i<=n; i++){
			dp_y[i][1]=a[i][1];
			for(j=2; j<=m; j++){
				dp_y[i][j]=max(dp_y[i][j-1], dp_y[i][j-2]+a[i][j]);
			}
		}
		memset(ans, 0, sizeof(ans));
		ans[1]=dp_y[1][m];
		for(i=2; i<=n; i++){
			ans[i]=max(ans[i-1], ans[i-2]+dp_y[i][m]);
		}
		printf("%d\n", ans[n]);
	}
	return 0;
}


NYOJ 吃土豆(动态规划)

标签:

原文地址:http://blog.csdn.net/shiwaigaoren12345/article/details/51340853

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!