数字金字塔(进阶)


Description

考虑在下面被显示的数字金字塔。
写一个程序来计算从最高点开始在底部任意处结束的路径经过数字的和的最大。
每一步可以走到左下方的点也可以到达右下方的点。

7 
3 8 
8 1 0 
2 7 4 4 
4 5 2 6 5 

在上面的样例中,从7 到 3 到 8 到 7 到 5 的路径产生了最大和:30

Input

第一个行包含 R(1<= R<=1000) ,表示行的数目。
后面每行为这个数字金字塔特定行包含的整数。
所有的被供应的整数是非负的且不大于100。

Output

单独的一行包含那个可能得到的最大的和。

Sample Input

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

Sample Output

30

解题思路

这道题与上一道数字金字塔不同,这道题的数据更大,所以如果用上一道题的方式会超时,所以我们就要考虑用动态规划。它的状态转移方程是:
a [ x ] [ y ] = m a x ( a [ x + 1 ] [ y ] , a [ x + 1 ] [ y + 1 ] ) + a [ x ] [ y ] a[x][y]=max(a[x+1][y],a[x+1][y+1])+a[x][y] a[x][y]=max(a[x+1][y],a[x+1][y+1])+a[x][y]
1 ≤ x ≤ r 1≤x≤r 1xr
1 ≤ y ≤ r 1≤y≤r 1yr
从下到上推:

#include<iostream>
#include<iomanip>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
int a[1005][1005],b[1005][1005],n,t=0;
int DP(int x,int y)
{
   
	a[x][y]=max(a[x+1][y],a[x+1][y+1])+a[x][y];//状态转移方程
} 
int main()
{
   
	cin>>n;
	for(int i=1;i<=n;i++) 
	 for(int j=1;j<=i;j++)
	  scanf("%d",&a[i][j]);//注意要用scanf,不然会超时
	for(int i=n-1;i>=1;i--)
	{
   
		for(int j=1;j<=i;j++)
		{
   
			DP(i,j);//动态规划
		}
	}
	printf("%d",a[1][1]);//输出第一个
	return 0;
}

从上到下推:

#include<iostream>
#include<iomanip>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
int maxn=0,a[1005][1005],n,t=0;
int DP(int x,int y)
{
   
	a[x][y]=max(a[x-1][y],a[x-1][y-1])+a[x][y];
} 
int main()
{
   
	cin>>n;
	for(int i=1;i<=n;i++) 
	 for(int j=1;j<=i;j++)
	  scanf("%d",&a[i][j]);
	for(int i=2;i<=n;i++)//从上往下
	{
   
		for(int j=1;j<=i;j++)
		{
   
			DP(i,j);
		}
	}
	for(int i=1;i<=n;i++)
	  if(a[n][i]>maxn) maxn=a[n][i];
	cout<<maxn;
	return 0;
}