博客
关于我
POJ-1163-The Triangle
阅读量:804 次
发布时间:2023-03-03

本文共 867 字,大约阅读时间需要 2 分钟。

要解决这个问题,我们需要找到从三角形的顶点走到最底层时所能获得的最大值。每一步只能向左下方或右下方走。我们可以使用动态规划来解决这个问题。

思路

我们可以使用动态规划来解决这个问题。具体来说,我们从顶点开始,逐层计算每个点的最大值。每个点的值是其上方左右两个点中的较大者加上自身的值。这样,我们就能确保每一步都能得到最大的可能值。

代码

#include 
#include
#include
#include
#include
#include
#include
#include
using namespace std;typedef long long LL;const int MAXN = 100 + 10;int a[MAXN][MAXN];int main() { int n; cin >> n; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= i; ++j) { cin >> a[i][j]; } } int res = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= i; ++j) { a[i][j] += max(a[i-1][j], a[i-1][j-1]); if (a[i][j] > res) { res = a[i][j]; } } } cout << res << endl; return 0;}

解释

  • 输入读取:首先读取输入的三角形大小 n 和每个点的值。
  • 初始化:我们使用一个二维数组 a 来存储每个点的值。
  • 动态规划计算:从顶点开始,逐层计算每个点的最大值。每个点的值是其上方左右两个点中的较大者加上自身的值。
  • 结果输出:在计算完所有点的值后,输出最大的值。
  • 通过这种方法,我们可以高效地计算出从顶点走到最底层时的最大值。

    转载地址:http://sbxfk.baihongyu.com/

    你可能感兴趣的文章
    python | pyautogui,一个超酷的 Python 库!
    查看>>
    python | pybaobabdt,一个超强的 决策树可视化 Python 库!
    查看>>
    python | pycco,一个神奇的 Python 库!
    查看>>
    python | pyg2plot,一个有趣的 数据可视化 Python 库!
    查看>>
    python | pymc,一个超强的 Python 库!
    查看>>
    python | pynsist,一个强大的 Python 库!
    查看>>
    python | pyparsing,一个强大的 Python 库!
    查看>>
    python | pyqtgraph,一个神奇的 Python 库!
    查看>>
    python读取文本文件数据
    查看>>
    python | Python mock对象与测试替身
    查看>>
    python | Python pandas实现数据追加和合并的最佳方法
    查看>>
    python | Python 中检查一个数字是否是三态数
    查看>>
    python | Python 蒙特卡洛模拟
    查看>>
    python | python-docx,一个超厉害的 Python 库!
    查看>>
    python | Python中使用@property装饰器
    查看>>
    python | Python中的functools模块高级应用
    查看>>
    python | Python中的itertools模块使用技巧
    查看>>
    python | Python中的事件驱动编程模型
    查看>>
    python | Python中的内存池与缓存机制
    查看>>
    python | Python中的弱引用与内存管理
    查看>>