2020 11th Blue Bridge Cup Provincial Competition Python Group (Real Question + Analysis + Code): Digital Triangle

  Hello everyone, I am Xiaolan who loves to share, welcome to exchange and correct~ 


1 Zhenti

enter

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

output

27

2 Analysis

Difficulty factor : ⭐⭐

Exam Question Type: Dynamic Programming

Knowledge points involved: modules

Thought analysis:

1. Loop through

When encountering pyramid-shaped data, first build a double for loop, traverse each number, and perform a sum calculation O(∩_∩)O

2. Recursion formula

There are three cases for summation: the element is at the leftmost or the middle or the rightmost

3. Print the answer

The final print needs to be classified discussion, odd and even.

Because the title requires: "The difference between the number of times of going down to the left and the number of times of going down to the right cannot exceed 1"

Follow this rule for a while, and you will find that the answer must fall in the middle.

If n is an odd number, it will inevitably go to the middle number a[-1][n//2] in the first last row
and if n is an even number, take the maximum value of the middle two numbers max(a[-1 ][n//2-1],a[-1][n//2])


3 code

#DP-数字三角形
n=int(input())#5
dp=[list(map(int,input().split())) for i in range(n)]
for i in range(1,n):                      #1~n-1
    for j in range(i+1):                  #0~i 
        if j==0:                          #最左边元素只能由右上方得到
            dp[i][j]+=dp[i-1][j]
        elif j==i:                        #最右边元素只能由左上方得到
            dp[i][j]+=dp[i-1][j-1]
        else:                             #中间元素取上方相邻两个最大值
            dp[i][j]+=max(dp[i-1][j-1],dp[i-1][j])
if n%2==1:                                #奇数行,返回中间值
    print(dp[-1][n//2])
else:                                     #偶数行,返回中间两个的最大值
    print(max(dp[-1][n//2-1],dp[-1][n//2])) #27
'''样例输入      样例输出           样例输入     样例输出  
i\j 0 1 2 3 4   0  1  2  3  4     0 1 2 3    0  1  2  3 
0   7           7                 7          7
1   3 8         10 15             3 8        10 15 
2   8 1 0       18 16 15          8 1 0      18 16 15
3   2 7 4 4     20 25 20 19       2 7 4 4    20 25 20 19
4   4 5 2 6 5   24 30 27 26 24     
'''


   Read tens of thousands of lines of code, press the button like a god, roll up your sleeves and work hard!

Blue Bridge Cup Python Group 11th Provincial Competition Zhenti + Analysis + Code (easy-to-understand version) Make a house number. This street has a total of 2020 residents, with house numbers from 1 to 2020. Little Blue has a matrix of numbers that only contain numbers 0 and 2. Xiaolan exercises every day. Under normal circumstances, Xiaolan runs 1 km a day. As shown in the figure below, Xiao Ming fills an infinite matrix with a positive integer "snake" starting from 1. https://blog.csdn.net/m0_55148406/article/details/122863264?spm=1001.2014.3001.5502

Guess you like

Origin blog.csdn.net/m0_55148406/article/details/122750260