tyvj 1044 数字三角形 记忆化搜索

数字三角形

Time Limit: 1 Sec  Memory Limit: 162 MB

题目连接

http://www.tyvj.cn/p/1044

Description

示出了一个数字三角形。 请编一个程序计算从顶至底的某处的一条路
径,使该路径所经过的数字的总和最大。
  每一步可沿左斜线向下或右斜线向下走;
  1<三角形行数<25;
  三角形中的数字为整数<1000;

Input

第一行为N,表示有N行
后面N行表示三角形每条路的路径权1n,m100000,0ai100000,1xin,0wi10000,1lirin

Output

路径所经过的数字的总和最大的答案

Sample Input

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

Sample Output

30

HINT

题解:

dp[i][j]表示从(i,j)这个位置出发后所能拿到的最大值

简单递推关系

代码:

//qscqesze
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
typedef long long ll;
using namespace std;
//freopen("D.in","r",stdin);
//freopen("D.out","w",stdout);
#define sspeed ios_base::sync_with_stdio(0);cin.tie(0)
#define maxn 2001
#define mod 10007
#define eps 1e-9
//const int inf=0x7fffffff;   //无限大
const int inf=0x3f3f3f3f;
/*

*/
//**************************************************************************************
inline ll read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int dp[maxn][maxn];
int g[maxn][maxn];
int main()
{
    int n=read();
    for(int i=1;i<=n;i++)
        for(int j=1;j<=i;j++)
            g[i][j]=read();
    for(int j=1;j<=n;j++)
        dp[n][j]=g[n][j];
    for(int i=n-1;i>=1;i--)
        for(int j=1;j<=n;j++)
            dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+g[i][j];
    printf("%d
",dp[1][1]);
}
原文地址:https://www.cnblogs.com/qscqesze/p/4384286.html