LightOJ 1004 Monkey Banana Problem (DP 数字三角形)

1004 - Monkey Banana Problem
Time Limit: 2 second(s)Memory Limit: 32 MB

You are in the world of mathematics to solve the great "MonkeyBanana Problem". It states that, a monkey enters into a diamond shaped twodimensional array and can jump in any of the adjacent cellsdown fromits current position (see figure). While moving from one cell to another, themonkey eats all the bananas kept in that cell. The monkey enters into the arrayfrom the upper part and goes out through the lower part. Find the maximumnumber of bananas the monkey can eat.

Input

Input starts with an integer T (≤ 50),denoting the number of test cases.

Every case starts with an integer N (1 ≤ N ≤100). It denotes that, there will be2*N - 1 rows. The ith(1 ≤ i ≤ N) line of nextN lines contains exactlyinumbers. Then there will beN - 1 lines. The jth (1≤ j < N) line containsN - j integers. Each number isgreater than zero and less than 215.

Output

For each case, print the case number and maximum number ofbananas eaten by the monkey.

Sample Input

Output for Sample Input

2

4

7

6 4

2 5 10

9 8 12 2

2 12 7

8 2

10

2

1

2 3

1

Case 1: 63

Case 2: 5

Note

Dataset is huge, use faster I/O methods.


题目链接:http://lightoj.com/volume_showproblem.php?problem=1004


题目大意:求从上往下路径的最大权值。

解题思路:数字三角形的变形,把菱形分为上下两部分求即可。dp[i][j]表示路径到第i行第j个点的最大权值和。
首先输入正三角,j=1时:dp[i][j] = dp[i-1][j];
     j=n时:dp[i][j] = dp[i-1][j-1];
     j=2~n-1: dp[i][j]=max(dp[i-1][j],dp[i-1][j-1]);
然后输入倒三角,dp[i][j]=max(dp[i-1][j],dp[i-1][j+1]);

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;
int a[102][102],dp[102][102];
int main()
{
    int i,j,t,n,cnt=0;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(i=1;i<=n;i++)
            for(j=1;j<=i;j++)
            scanf("%d",&a[i][j]);
        dp[1][1]=a[1][1];
        for(i=2;i<=n;i++)
            for(j=1;j<=i;j++)
            {
                if(j==1)
                    dp[i][j]=a[i][j]+dp[i-1][j];
                else if(j==n)
                    dp[i][j]=a[i][j]+dp[i-1][j-1];
                else
                    dp[i][j]=a[i][j]+max(dp[i-1][j-1],dp[i-1][j]);
            }
        for(i=n-1;i>=1;i--)
            for(j=1;j<=i;j++)
                scanf("%d",&a[i][j]);
        for(i=n-1;i>=1;i--)
            for(j=1;j<=i;j++)
                dp[i][j]=a[i][j]+max(dp[i+1][j],dp[i+1][j+1]);
        printf("Case %d: %d\n",++cnt,dp[1][1]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值