Euler project #18 approach

后端 未结 9 865
鱼传尺愫
鱼传尺愫 2020-11-30 22:23

I am looking into an Euler project. Specifically #18.
To sum up, the idea is to find the max path from a triangle:

   3
  7 4
 2 4 6  
8 5 9 3
<         


        
相关标签:
9条回答
  • 2020-11-30 23:06

    This is a problem that can be solved using graph theory. For each point, you can only travel to each of it's two 'children' (the left and right node below it). For all of the leaf nodes (the bottom row) include a path to an "end node" (with zero cost).

    You want the largest number, which in turn is the longest path.

    To do this, you implement a BFS (which is generally a shortest path algorithm), but instead of having the weight between a parent and child node being the value of the child node, you make it be the additive inverse of the child nodes value.

    You cannot use Dijkstra easily here because Dijkstra is for non-negative paths only.

    BFS has running time of O(|E|+|V|).
    In a triangle there are 1+2+3+4+5+..+n = (1/2)(n)(n-1) nodes
    This means that there are (n)(n-1) paths, plus the (n) for the final node connection
    Total: (1/2)
    (3n^2 -n) where n is the number of rows.

    0 讨论(0)
  • 2020-11-30 23:09

    Since the rows are small in number you can use also recursion to compute the greatest sum :

    import sys
    def max_sum(i,j):
        if i==14:
            return a[i][j]
        return a[i][j]+max(max_sum(i+1,j),max_sum(i+1,j+1))
    a=[]
    for i in range(15):
        b=list(map(int,sys.stdin.readline().split()))
        a.append(b)
    print(max_sum(0,0))
    

    for question 67 -(Maximum path sum II) you can use memoisation:

    import sys
    d={}
    def max_sum(i,j):
        if (i,j) in d:
            return d[(i,j)]
        if i==99:
            return a[i][j]
        d[(i,j)]=a[i][j]+max(max_sum(i+1,j),max_sum(i+1,j+1))
        return d[(i,j)]
    a=[]
    for i in range(100):
        b=list(map(int,sys.stdin.readline().split()))
        a.append(b)
    print(max_sum(0,0))
    
    0 讨论(0)
  • 2020-11-30 23:13

    Using your example, the "bottom up" way to approach it is:

    Examining the bottom row, the most you can get from each element is

    8,5,9,3

    Examining the next-to-bottom row, the most you can get from each element is (depending on whether you go left or right from it):

    2+max(8,5),4+max(5,9),6+max(9,3) = 10,13,15

    So this is great; we've eliminated 2 rows by squishing them together to replace them with one row, reducing the problem to

         3
       7   4
    10  13  15
    

    Obviously we can just keep repeating this. Examining the next row up, the most you can get from each element is

    7+max(10,13),4+max(13,15) = 20,19

    And so from the top, the most you can get is

    3+max(20,19) = 23

    QED.

    0 讨论(0)
提交回复
热议问题