The Triangle

                           The Triangle

    Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u

 

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

【解法一】

//这道题第一印象就是DFS,但一般的剪枝都会超时

//这里就用了记忆化搜索,dp[i][j]标记

 

# include<iostream>
# include<cstring>
using namespace std;
int sign[102][102];
int dp[102][102];
int nCase;
int dfs(int i,int j)//还是要加上DFS的深搜递归思想
{
    int a,b;
    if(i==nCase+1)return 0;
    if(dp[i][j]!=-1)return dp[i][j];//这就是记忆化搜索的精华部分,以前被搜到过,这次也一定能搜到
    a=dfs(i+1,j);
    b=dfs(i+1,j+1);
    if(a<b)a=b;//这就算是做了一下处理,这样每次搜过就不在搜了
    return dp[i][j]=a+sign[i][j];
}
int main()
{
    int i,j;
    memset(sign,0,sizeof(sign));
    memset(dp,0,sizeof(dp));
    cin>>nCase;
    for(i=0;i<nCase;i++)
    {
        for(j=0;j<=i;j++)
        {
            cin>>sign[i][j];
            dp[i][j]=-1;
        }
    }
    cout<<dfs(0,0)<<endl;
    return 0;
}

 

 【解法二】

//用正式的动归来做

//这种方法灵活,可以根据题意的改变,做相应的变化;但用时要比第一种多

 

# include<stdio.h>
# include<string.h>
#define N 105
int n, dp[N][N];
int tmax(int a,int b)
{
    return a>b?a:b;
}
void Dp()
{
    int i, j;
    for (i = n-1; i >= 1; i--)
    {
        for (j = 1; j <= i; j++)
        {
            dp[i][j]+=tmax(dp[i+1][j+1], dp[i+1][j]);
        }
    }
    printf("%d\n", dp[1][1]);
}
int main()
{
    int i, j;
    scanf("%d", &n);
        for (i = 1; i <= n; i++)
        {
            for (j = 1; j <= i; j++)
            {
                scanf("%d", &dp[i][j]);
            }
        }
        Dp();
    return 0;
}

 

posted on 2012-08-11 23:36  即为将军  阅读(236)  评论(0)    收藏  举报

导航