Blue Bridge Cup Test Questions: Digital Triangle

Digital triangle

Problem Description

Given a "digital triangle" with a height of n, there are i numbers in the i-th row (1<=i<=n).
Initially, you stand on the top of the "digital triangle", the only number in the first row. Each time you move, you can choose to move to a position directly below the current position or to the lower right of the current position. That is, if you are at (i,j) (indicating that you count the jth number from left to right in the i-th row, the same below), you can choose to move to (i+1,j) or (i+1,j +1).
You want to maximize the sum of all the positions (including the start and end points) you pass. Find this maximum value.

Input format

A positive integer n in the first line represents the size of the digital triangle.

From line 2 to line n+1, line i+1 is a non-negative integer separated by spaces , describing the i-th line of the digital triangle.

Output format

An integer per line represents the maximum sum of the numbers on the path.

Sample input

4

1

2 3

4 5 6

7 8 9 10

Sample output

20

Sample explanation

Just keep walking down to the right.

Method One
Idea:

This question can use the recursive form, you can take out the left and right of each layer and then judge the size, adding the large number to the sum of the level numbers. We can create a two-dimensional array to memorize each result. If maxSum[r+1][j]==-1 This judgment is used to subtract repeated calculations.

a=int(input())
dp=[]
for i in range(a):
   dp.append(list(map(int,input().split())))
maxSum=[[-1 for i in range(a)]for i in range(a)]
def ma(r,j):
   if r==a-1:
       return dp[r][j]
   if maxSum[r+1][j]==-1:   #如果MaxSum(r+1,j)没有计算过,计算后保存 
       maxSum[r+1][j]=ma(r+1,j);
   if maxSum[r+1][j+1]==-1:   #如果MaxSum(r+1,j+1)没有计算过,计算后保存 
       maxSum[r+1][j+1]=ma(r+1,j+1);
   if maxSum[r+1][j]>maxSum[r+1][j+1]:
       return maxSum[r+1][j]+dp[r][j];
   return maxSum[r+1][j+1]+dp[r][j];

print(ma(0,0))

Method 2
Idea
:
The following code is typed in the form of dynamic programming. I use the recursive method to go from the bottom to the first. The transfer equation of this program is q[i-1][i1]+=max(q[i ][i1],q[i][i1+1]), let the bottom layer continuously take the maximum of 2 results to his superior. So the best value is to go to q[0][0].

a=int(input())
q=[]
q1=[[0 for i1 in range(i)] for i in range(1,a)]
for i in range(a):
    q.append(list(map(int,input().split())))

for i in range(a-1,0,-1):
    for i1 in range(i):
        q[i-1][i1]+=max(q[i][i1],q[i][i1+1])
print(q[0][0])

Reprinting is prohibited. Only for self-study. No responsibility for program errors.

Guess you like

Origin blog.csdn.net/weixin_46640345/article/details/112426502