Trying to Understand the Logic

时间:2017-05-16 09:21:37

标签: algorithm logic

Let's consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line, three in the third line, etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that on each path the next number is located on the row below, more precisely either directly below or below and one place to the right; the number of rows is strictly positive, but less than 100; all numbers are positive integers between 0 and 99.

Input :: In the first line integer n - the number of test cases (equal to about 1000). Then n test cases follow. Each test case starts with the number of lines which is followed by their content.

Output :: For each test case write the determined value in a separate line.

Example

Input:
2
3
1
2 1
1 2 3
4 
1 
1 2 
4 1 2
2 3 1 1 

Output:
5
9

My Question is How is the output given as 5 and 9?

2 个答案:

答案 0 :(得分:0)

The first output is 5. Let's see, you have the following triangle (since the first line is the number of triangles in the input, 2, and the second line the height of the next pyramid, 3):

1
2 1
1 2 3

You start at the first line and always go either straight down or down+one to the right, summing numbers on the way.

There are many solutions here:

  • always down: 1+2+1 = 4
  • always right: 1+1+3 = 5
  • down, then right: 1+2+2=5
  • ...

So the best you can do is 5.

The same logic applies to the second triangle:

1 
1 2 
4 1 2
2 3 1 1 

The best is 1+1+4+3=9, i.e. down,down,right.

答案 1 :(得分:0)

正如其中一个答案所述,我们必须检查所有可能性,但在这种方法中并不是必需的 它起作用 -

  • 从倒数第二行开始,并为该行中的每个元素开始 检查元素可以产生的最大总和并替换 最大的元素。

  • 对上面的行重复该过程,最后我们得到了 考虑最顶层可以达到的最大值 元件。 上述方法是动态编程方法 这个解决方案具有复杂度O(元素数量),但如果我们检查所有可能性,那么它将给出一个指数解 可以通过以下方式达成解决方案 -

考虑输入

    1
    2 1
    1 2 3

考虑倒数第二行 -
现在考虑如果我们的路径以某种方式包含该行的1 st 元素的情况,那么考虑到该元素可以实现的最大值是 - max(2+1,2+2) = 4并且如果某种程度上我们的路径具有2考虑到该元素为max(1+2,1+3) = 4,该行的 nd 元素是我们可以实现的最大值。
现在我修改三角形如图所示 -

1
4 4


现在考虑上一行(仅有一个元素)上方的行 为此,如果在我们的路径中取1,则可以实现的最大总和是 - max(1+4,1+4) = 5 所以对此,答案是5。

对于第二种情况 -

1 
1 2 
4 1 2
2 3 1 1

在考虑倒数第二行后,三角形看起来像 -

1 
1 2 
7 4 3

4 - 由max(4 + 2,4 + 3)替换 1 - 由max(1 + 3,1 + 1)替换 2 - 由max(2 + 1,2 + 1)替换
现在是它上面的行 -

1 
8 6 

最后 -

9

所以答案是9。

以下是与上述问题相同的问题的链接 - https://www.hackerrank.com/contests/projecteuler/challenges/euler018