Number Triangles

题目描述

Consider the number triangle shown below. Write a program that calculates the highest sum of numbers that can be 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.
          7
        3   8
      8   1   0
    2   7   4   4
  4   5   2   6   5
In the sample above, the route from 7 to 3 to 8 to 7 to 5 produces the highest sum: 30.
 

输入

The first line contains R (1 <= R <= 1000), the number of rows. Each subsequent line contains the integers for that particular row of the triangle. All the supplied integers are non-negative and no larger than 100.

输出

A single line containing the largest sum using the traversal specified.

样例输入

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

样例输出

30

分析:

我就说是个DP题,递什么归递归。

dp[i][j]表示从底层走到达坐标[i][j]的最大值,从底向上扫,状态转移方程为dp[i][j]+=max(dp[i+1][j],dp[i+1][j+1])。

#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#define range(i,a,b) for(int i=a;i<=b;++i)
#define rerange(i,a,b) for(int i=a;i>=b;--i)
#define fill(arr,tmp) memset(arr,tmp,sizeof(arr))
using namespace std;
int n,dp[1005][1005];
void init(){
    cin>>n;
    range(i,1,n)range(j,1,i)cin>>dp[i][j];
    rerange(i,n-1,1)
    range(j,1,i)dp[i][j]+=max(dp[i+1][j],dp[i+1][j+1]);
}
void solve(){
    cout<<dp[1][1]<<endl;
}
int main() {
    init();
    solve();
    return 0;
}
原文地址:https://www.cnblogs.com/Rhythm-/p/9324701.html