描述 Description | |||
示出了一个数字三角形。 请编一个程序计算从顶至底的某处的一条路 径,使该路径所经过的数字的总和最大。 每一步可沿左斜线向下或右斜线向下走; 1<三角形行数<25; 三角形中的数字为整数<1000; |
输入格式 Input Format | |||
第一行为N,表示有N行 后面N行表示三角形每条路的路径权 |
输出格式 Output Format | |||
路径所经过的数字的总和最大的答案 |
样例输入 Sample Input | |||
样例输出 Sample Output | |||
注释 Hint | |||
搜索80分,记忆化搜索AC |
#include <iostream> //动态规划
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
int A[26][26],B[26][26];
int n;
int d(int i,int j)
{
if(B[i][j]>=0) return B[i][j]; //记忆化搜索
else
{
return B[i][j]=A[i][j]+(i==n-1?0:(d(i+1,j)>d(i+1,j+1)?d(i+1,j):d(i+1,j+1))); //状态转移方程
}
}
int main ()
{
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<=i;j++)
scanf("%d",&A[i][j]);
memset(B,-1,sizeof(B));
cout<<d(0,0)<<endl;
system("pause");
return 0;
}