动态规划入门
例1:
def jianshuiguo(n,ans): dp=[[0 for i in range(n+1)]for j in range(n+1)] dp[1][0]=ans[1][0] # print(dp) sum=0 for i in range(2,n+1): for j in range(i): if j==0: dp[i][j]=dp[i-1][j]+ans[i][j] elif i==j-1: dp[i][j]=dp[i-1][j-1]+ans[i][j] else: dp[i][j]=max(dp[i-1][j],dp[i-1][j-1])+ans[i][j] if i==n: if sum<dp[i][j]: sum=dp[i][j] return sum if __name__=='__main__': n=int(input()) ans=[] ans.append([0]*(n+1)) for i in range(n): ans.append(list(map(int,input().rstrip().split()))) for j in range(len(ans)): while len(ans[j])<n+1: ans[j].append(0) # print(ans) print(jianshuiguo(n,ans))
例2:
def taosheng(n,m,x,y,v,c,ans): dp=[[0 for i in range(n)]for j in range(m)] sum=0 # #左上 for i in range(x,-1,-1): for j in range(y,-1,-1): if i==x and j==y: dp[i][j]=v+ans[i][j] elif i==x: dp[i][j]=dp[i][j+1]+ans[i][j] elif j==y: dp[i][j]=dp[i+1][j]+ans[i][j] else: dp[i][j]=max(dp[i+1][j],dp[i][j+1])+ans[i][j] if dp[i][j]>c: dp[i][j]=c if dp[i][j]<=0: dp[i][j]=-1000000000 # 左下 for i in range(x,n): for j in range(y,-1,-1): if i==x and j==y: dp[i][j]=v+ans[i][j] elif i==x: dp[i][j]=dp[i][j+1]+ans[i][j] elif j==y: dp[i][j]=dp[i-1][j]+ans[i][j] else: dp[i][j]=max(dp[i][j+1],dp[i-1][j])+ans[i][j] if dp[i][j]>c: dp[i][j]=c if dp[i][j]<=0: dp[i][j]=-1000000000 #右上 for i in range(x,-1,-1): for j in range(y,m): if i==x and j==y: dp[i][j]=v+ans[i][j] elif i==x: dp[i][j]=dp[i][j-1]+ans[i][j] elif j==y: dp[i][j]=dp[i+1][j]+ans[i][j] else: dp[i][j]=max(dp[i][j-1],dp[i+1][j])+ans[i][j] if dp[i][j]>c: dp[i][j]=c if dp[i][j]<=0: dp[i][j]=-1000000000 #右下 for i in range(x,n): for j in range(y,m): if i==x and j==y: dp[i][j]=v+ans[i][j] elif i==x: dp[i][j]=dp[i][j-1]+ans[i][j] elif j==y: dp[i][j]=dp[i-1][j]+ans[i][j] else: dp[i][j]=max(dp[i][j-1],dp[i-1][j])+ans[i][j] if dp[i][j]>c: dp[i][j]=c if dp[i][j]<=0: dp[i][j]=-1000000000 sum=max(max(dp[0][0],dp[n-1][m-1]),max(dp[0][m-1],dp[n-1][0])) return sum if sum>0 else -1 if __name__=='__main__': n,m,x,y,v,c=map(int,input().split()) ans=[] for i in range(n): ans.append(list(map(int,input().rstrip().split()))) print(taosheng(n,m,x-1,y-1,v,c,ans))