【简单】动态规划数字三角形

例题一:数字三角形(POJ1163)

The Triangle

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 8321 Accepted: 35029

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

题意:在上面的数字三角形中寻找一条从顶部到底边的路径,使得路径上所经过的数字之和最大。路径上的每一步都只能往左下或右下走,比如数字3只可以走到8和1,只需求出这个最大和即可,不必给出具体路径

三角形的行数小于等于100,数字为0-99

数字之和int就能放得下

思路:这道题看上去可以用递归,D(r,j) 第r行第j个数字,从1开始。maxsum(i,j)是从d(i,j)到底边的各条路径中,最佳路径之和,从D(i,j)出发,只有两条路D(i+1,j)和D(i+1,j+1),故可以写出递推式

if(r==N)

maxsum(r,j)=D(i,j)

else

maxsum(r,j)=max(maxsum(r+1,j),maxsum(r+1,j+1))+D(i,j)

这样看上去是不是很简单,但是这样做提交到OJ会超时,如果采用递归的方法,深度遍历每条路径,每个数字的maxsum(i,j)可能会被计算多次,存在大量重复计算,则时间复杂度为2^n.对于n=100行,肯定超时。

故此题应该用动态规划,每算出一个maxsum(i,j)就保存起来,下次用到其值时直接取用,则可免去重复计算,那么可以用         O(n^2)时间完成计算,因为三角形的数字总数是n(n+1)/2,每个数字都要算一次maxsum(i,j)

代码如下

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
const int N=1000;
int maxsum[N][N];
int d[N][N];
int n;
using namespace std;
int Maxsum(int i,int j)
{
    if(maxsum[i][j]!=-1)
        return maxsum[i][j];//已经计算过maxsum的值,不需要再计算,避免了重复计算
    if(n==1)
        return d[i][j];
    else
    {
        maxsum[i][j]=max(Maxsum(i+1,j),Maxsum(i+1,j+1))+d[i][j];
    }
    return maxsum[i][j];
}
int main()
{

    cin>>n;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=i;j++)
        {
            cin>>d[i][j];
            maxsum[i][j]=-1;

        }
    }

    cout<<Maxsum(1,1);
    return 0;
}

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值