Files
SolutionEuler/solutions/0067.MaxPathSum2/eular_67.py
Sidney Zhang 9a43e5e68b feat(pyproject.toml):添加mplusa依赖用于最大路径和计算
 feat(solutions):新增欧拉问题17、18和67的解决方案
📝 docs(solutions/0018.MaxPathSum1):添加说明文档指出初始解法存在局部最优问题
 feat(solutions/0067.MaxPathSum2):实现基于最大加代数的优化解法
2025-12-17 18:20:20 +08:00

47 lines
1.1 KiB
Python

"""
By starting at the top of the triangle below and moving to adjacent numbers on the row below,
the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23 .
Find the maximum total from top to bottom of the triangle in the file 0067_trangle.txt.
"""
from pathlib import Path
import numpy as np
from mplusa import maxplus as mp
def triangle_best(triangle: list[list[int]]) -> int:
levels = len(triangle)
current = np.array(triangle[-1], dtype=float).reshape(-1, 1)
for i in range(levels - 2, -1, -1):
selector = np.full((i + 1, i + 2), -np.inf)
np.fill_diagonal(selector, triangle[i])
np.fill_diagonal(selector[:, 1:], triangle[i])
current = mp.mult_matrices(selector, current)
print(current)
return int(current[0][0])
def main() -> None:
with open(Path(__file__).parent / "0067_triangle.txt", "r") as file:
data = file.read().split("\n")[:100]
triangle = [list(map(int, row.split())) for row in data]
res = triangle_best(triangle)
print(res)
if __name__ == "__main__":
main()