Project Euler problem 67: find maximum cost path in 100-row triangle

前端 未结 5 1160
长情又很酷
长情又很酷 2021-02-11 06:27

In Project Euler\'s problem 67 there is a triangle given and it contains 100 rows. For e.g.

        5
      9  6
    4   6  8
  0   7  1   5

I.e. 5 + 9 + 6 + 7          


        
5条回答
  •  迷失自我
    2021-02-11 07:01

    You want to store this as a directed acyclic graph. The nodes are the entries of your triangular array, and there is an arrow from i to j iff j is one row lower and immediately left or right of i.

    Now you want to find the maximum weight directed path (sum of the vertex weights) in this graph. In general, this problem is NP-complete, however, as templatetypedef points out, there are efficient algorithms for DAGs; here's one:

    algorithm dag-longest-path is
        input: 
             Directed acyclic graph G
        output: 
             Length of the longest path
    
        length_to = array with |V(G)| elements of type int with default value 0
    
        for each vertex v in topOrder(G) do
            for each edge (v, w) in E(G) do
                if length_to[w] <= length_to[v] + weight(G,(v,w)) then
                    length_to[w] = length_to[v] + weight(G, (v,w))
    
        return max(length_to[v] for v in V(G))
    

    To make this work, you will need to weight the length of the path to be the size of the target node (since all paths include the source, this is fine).

提交回复
热议问题