51Nod 1002:数塔取数问题(DP)

1002 数塔取数问题 

基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题

 收藏

 关注

一个高度为N的由正整数组成的三角形,从上走到下,求经过的数字和的最大值。

每次只能走到下一层相邻的数上,例如从第3层的6向下走,只能走到第4层的2或9上。

   5

  8 4

 3 6 9

7 2 9 5

例子中的最优方案是:5 + 8 + 6 + 9 = 28

Input

第1行:N,N为数塔的高度。(2 <= N <= 500)
第2 - N + 1行:每行包括1层数塔的数字,第2行1个数,第3行2个数......第k+1行k个数。数与数之间用空格分隔(0 <= A[i] <= 10^5) 。

Output

输出最大值

Input示例

4
5
8 4
3 6 9
7 2 9 5

Output示例

28

HDU1176基本一样。从最后一行往前走。状态转移方程:dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])

AC代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <string>
#define ll long long
#define ms(a) memset(a,0,sizeof(a))
#define pi acos(-1.0)
#define INF 0x3f3f3f3f
const double E=exp(1);
const int maxn=1e3+10;
using namespace std;
int dp[maxn][maxn];
int main(int argc, char const *argv[])
{
	ios::sync_with_stdio(false);
	int n;
	int m=0;
	ms(dp);
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		m+=1;
		for(int j=1;j<=m;j++)
		{
			cin>>dp[i][j];
		}
	}
	for(int i=n;i>=1;i--)
	{
		for(int j=m;j>=1;j--)
		{
				dp[i][j]+=max(dp[i+1][j],dp[i+1][j+1]);
		}
		m--;
	}
	cout<<dp[1][1]<<endl;
	return 0;
}
 

猜你喜欢

转载自blog.csdn.net/wang_123_zy/article/details/81383241