题目18:The Triangle

来源:互联网 发布:2017最新一元云购源码 编辑:程序博客网 时间:2024/05/29 23:45

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=18
描述
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.

输入
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.
输出
Your program is to write to standard output. The highest sum is written as an integer.
样例输入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
样例输出
30
算法思想:
使用动态规划,可以从底至上来进行填写备忘录,也可以自顶向下进行填写备忘录。这里运用的是自顶向下填写备忘录。
递推公式:dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1]) + a;
其中dp[i][j]代表的是第i行第j列位置记录的最大值,a代表的是当前输入的值。
这里写图片描述
如图所示,当输入的是a = 1时,比较dp[i - 1][j - 1]与dp[i - 1][j]的大小,并更新dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1]) + a.
源代码

#include <iostream>#include <algorithm>using namespace std;int dp[101][101];int main(){    int n, a;    cin >> n;    for (int i = 1; i <= n; i++)    {        for (int j = 1; j <= i; j++)        {            cin >> a;            dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1]) + a;        }    }    int max = 0;    for (int i = 1; i <= n; i++)    {        if (max < dp[n][i])            max = dp[n][i];    }    cout << max << endl;    return 0;}

算法时间复杂度: 有两层循环遍历,故时间复杂度为O(n^2)。