0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Project Euler】Problem 67: 経路の合計の最大値 (その2)

Posted at
  • 本記事はProjectEulerの「100番以下の問題の説明は記載可能」という規定に基づいて回答のヒントが書かれていますので、自分である程度考えてみてから読まれることをお勧めします。

問題 67. 経路の合計の最大値 (その2)

原文 Problem 67: Maximum path sum II

問題の要約:triangle.txtの100行のピラミッド型の数の上から下まで数字をたどった経路の合計の最大値を求めよ

これはProblem 18: 経路の合計の最大値 (その1)の拡大版と言えます。アルゴリズムはProblem 18と同じで良いので。データを同様な配列に入れればプロクラムにはそのままでOKです。

for y in range(len(triarr)-2,-1,-1):
  for x in range(y+1):
    triarr[y][x] += max(triarr[y+1][x],triarr[y+1][x+1])
print(f"Answer: {triarr[0][0]}")

ファイルから読んで配列に入れるプロクラム。

# show upload dialog
from google.colab import files
uploaded = files.upload()
#---- read numbers from file
f = open("p067_triangle.txt")
triNums = f.readlines()
f.close()
triarr = [list(map(int,row.split())) for row in triNums]
print(triarr[:20])

(開発環境:Google Colab)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?