Euler program (python) Problem 67

Source: Internet
Author: User

Maximum Path Sum Iiproblem 67

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top t O 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 in Triangle.txt (right click and ' Save link/target as ... '), a 15K text file cont Aining a triangle with one-hundred rows.

Note: This was a much more difficult version of problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is a efficient algorithm to solve it. ; o)


Go to the "thread for Problem" in the forum.

The Thinking of solving problems: Dynamic programming

Python code:

Import Math
Sqrt=math.sqrt


A=[]
f = open ("Data.txt")
line = F.readline ()
While line:
Row=line.split (")
For I in range (0,len (row)):
A.append (int (row[i]))
line = F.readline ()
F.close ()


K=len (a)
def getsun (x):
Redult=[];
K=int ((sqrt (1+8*x)-1)/2) +1
return [x+k,x+k+1]


def getrowstart (x):
return int (x* (x-1)/2)


For I in Range (99,0,-1):
Start=getrowstart (i)
For j in Range (0,i):
Sun=getsun (START+J)
A[start+j]+=max (A[sun[0]],a[sun[1])
Print (A[0])


Time: <1s

Euler program (python) Problem 67

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.