POJ 1163 The Triangle

Description

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

                                             (Figure 1)

Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right. 

Input

Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.

Output

Your program is to write to standard output. The highest sum is written as an integer.

Sample Input

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

Sample Output

30

Source

IOI 1994

解题思路:

以例题为例,多组数据不好考虑,先来看最上面两组。因为只能走左斜下,和右斜下,要求输出最大和,根7,左边3,右边8,所以我们的操作是返回 (根+左右两孩子较大的)。三层的时候也是一个道理,这是“人人为我的一种情况”,即本行的返回值,取决于下一行中较大的数。所以用递归的方法,从最后依次向上返回最大值。

注意:因为存在重复计算的情况,所以要用一个状态数组bp来标记从最底部到该点为止的最大和。

#include<cstdio>
#include<iostream>
#include<algorithm>
const int maxn = 100+10;
int D[maxn][maxn];
int bp[maxn][maxn];
int n;
using namespace std;
int MaxSum(int i,int j){
    if(bp[i][j] != -1)
        return bp[i][j];
    if(i == n)
        return bp[i][j] = D[i][j];
    int x = MaxSum(i+1,j);
    int y = MaxSum(i+1,j+1);
    return bp[i][j] = max(x,y) + D[i][j];
}
int main()
{
    scanf("%d",&n);
    for(int i = 1 ;i <= n;i++){
        for(int j = 1;j <= i;j++){
            scanf("%d",&D[i][j]);  //第i行的第j个数
            bp[i][j] = -1;
        }
    }
    printf("%d",MaxSum(1,1));
    return 0;
}

非递归(比较清晰):

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn = 100+10;
int dp[maxn][maxn];
int D[maxn][maxn];
int n;
int main()
{
    scanf("%d",&n);
    for(int i = 1;i <= n;i++)
        for(int j = 1;j <= i;j++){
            scanf("%d",&D[i][j]);
        }
    for(int i = 1;i <= n;i++){
        dp[n][i] = D[n][i];
    }
    for(int i = n-1;i >= 1;i--)
        for(int j = 1;j <= i;j++){
            dp[i][j] =  max(dp[i+1][j],dp[i+1][j+1]) + D[i][j];
    }
    printf("%d",dp[1][1]);
}

猜你喜欢

转载自blog.csdn.net/qq_42018521/article/details/81563755