The 11th provincial contest python test question H: digital triangle

Question H: Digital Triangle


【问题描述】
上图给出了一个数字三角形。从三角形的顶部到底部有很多条不同的路径。对于每条路径,把路径上面的数加起来可以得到一个和,你的任务就是找到最
大的和。
路径上的每一步只能从一个数走到下一层和它最近的左边的那个数或者右
边的那个数。此外,向左下走的次数与向右下走的次数相差不能超过 1。
【输入格式】
输入的第一行包含一个整数 N (1 < N ≤ 100),表示三角形的行数。下面的
N 行给出数字三角形。数字三角形上的数都是 0 至 100 之间的整数。
【输出格式】
输出一个整数,表示答案。
【样例输入】
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
【样例输出】
27

Method 1
Idea (recursion):
Use the form of recursion to complete the traversal from top to bottom, first create the function fin (x, y, c, dx, dl) x, y represent the position of the q list, c is the cumulative number, dx, dl represent the number of steps left and right. u=[[1,0],[1,1]] left and right positions, so that the function can continue to recurse all positions. The time complexity is all o(2**n)0.

program:

a=int(input())
q=[]
for _ in range(a):
    q.append(list(map(int,input().split())))
mx=0
u=[[1,0],[1,1]]
def fin(x,y,c,dx,dl):
    global mx
    for i in range(2):
        d=x+u[i][0]
        l=y+u[i][1]
        if d>=a:
            if mx<c and abs(dx-dl)<=1:
                mx=c
            return
        elif i==0:
            fin(d,l,c+q[d][l],dx+1,dl)
        else:
            fin(d,l,c+q[d][l],dx,dl+1)
fin(0,0,q[0][0],0,0)
print(mx)

Method Two

Ideas (dynamic programming):
DP derivation + parity judgment. When inputting an array, calculate the value of the array, because I can only go left or right, that is, the coordinates of my current position are the coordinates obtained by jumping from the left or above the position of the previous layer, by selecting the maximum value Jump and update the value of the array. Since the left and right cannot exceed 1, the number of layers is judged by parity. If it is an odd number, the last position is the a-th layer, and the number at the (a//2) position, if it is an even number , You need to determine the nth layer, the number at the (a/2-1) position and the number at the (a/2) position on the a layer, and choose the larger one.
Note that my array index starts from 0.

program:

a=int(input())
q=[]
for _ in range(a):
    q.append(list(map(int,input().split())))

for i in range(a):
    for i1 in range(i):
        try :
            q[i][i1]+=max(q[i-1][i1-1],q[i-1][i1])
        except:
            if i1==0:
                q[i][i1]=q[i-1][i1]
            else:
                q[i][i1]=q[i-1][i1-1]

         
print(q[a-1][int(a/2)] if a%2==1 else max(q[a-1][a/2-1],q[a-1][a/2]))
        

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

Guess you like

Origin blog.csdn.net/weixin_46640345/article/details/112391594
Recommended