洛谷 1.5.1 Number Triangles 数字金字塔

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

经典入门DP题。

如果从最后一层到第一层的话,第一层的数必然由第二层的最大的一个数(以下几层的和)相加而来,第二层同理,第三层如是。

有一个策略是肯定正确的,就是两个数相比,必然是取大的那个。

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<cstring>
 4 #include<string>
 5 #include<cmath>
 6 #include<algorithm>
 7 #include<queue>
 8 #include<stack>
 9 #include<deque>
10 #include<map>
11 #include<iostream>
12 using namespace std;
13 typedef long long  LL;
14 const double pi=acos(-1.0);
15 const double e=exp(1);
16 const int N = 10009;
17 
18 int dp[1004][1004];
19 int main()
20 {
21     int i,p,j;
22     int n,t;
23     scanf("%d",&n);
24     for(i=0;i<n;i++)
25     {
26         for(j=0;j<=i;j++)
27         {
28             scanf("%d",&dp[i][j]);
29         }
30     }
31     for(i=n-2;i>=0;i--)
32     {
33         for(j=0;j<=i;j++)
34         {
35             dp[i][j]+=max(dp[i+1][j],dp[i+1][j+1]);
36         }
37     }
38     printf("%d
",dp[0][0]);
39     return 0;
40 }
View Code
原文地址:https://www.cnblogs.com/daybreaking/p/9608733.html