row=int(input()) if row==0: print(0) else: dp=[[0 for i in range(row+1)] for j in range(row+1)] # python中创建二维列表 for i in range(row): line=input().split() for j in range(i+1): dp[i+1][j+1]=int(line[j]) # print(dp) for k in range(2,row+1): for p in range(1,k+1): dp[k][p]=max(dp[k-1][p-1],dp[k-1][p])+dp[k][p] last=dp[-1] max=-1 for elem in last: if elem>max: max=elem print(max) 此代码增加一段输出最大值路径的代码
时间: 2024-02-13 13:06:25 浏览: 104
解决出现Incorrect integer value: '' for column 'id' at row 1的问题
5星 · 资源好评率100%
要输出最大值路径,可以在动态规划过程中记录每个位置来自哪个位置,最终回溯路径即可。具体代码如下:
```
row=int(input())
if row==0:
print(0)
else:
dp=[[0 for i in range(row+1)] for j in range(row+1)]
path=[[-1 for i in range(row+1)] for j in range(row+1)] # 记录路径
for i in range(row):
line=input().split()
for j in range(i+1):
dp[i+1][j+1]=int(line[j])
for k in range(2,row+1):
for p in range(1,k+1):
if dp[k-1][p-1]>dp[k-1][p]:
dp[k][p]=dp[k-1][p-1]+dp[k][p]
path[k][p]=p-1
else:
dp[k][p]=dp[k-1][p]+dp[k][p]
path[k][p]=p
last=dp[-1]
max=-1
max_index=-1
for i, elem in enumerate(last):
if elem>max:
max=elem
max_index=i
# 回溯路径
res=[max_index]
for i in range(row-1,0,-1):
max_index=path[i+1][max_index+1]
res.insert(0,max_index)
print(max)
print('->'.join(str(x) for x in res))
```
在输出最大值之后,加上了一个回溯路径的过程,将路径按顺序输出即可。
阅读全文