【发布时间】:2014-02-04 05:13:57
【问题描述】:
在经典的切杆动态规划问题中 - 我在哪里切割长度为 n 的杆以最大化我通过出售整个杆或其中的部分获得的价格。另请参阅此处的问题陈述以获取详细信息 -Understanding the bottom-up rod cut implementation
我如何保留索引标签 - 即我在原始杆的哪个位置进行切割? 我似乎对知道如何保持杆最终被切割的索引没有一个公平的理解。 这是我的代码-:
# price is dict of revenue we get for the corresponding rod-length
price={1:1,2:5,3:8,4:9,5:10,6:17,7:17,8:20,9:24,10:30}
def cut_rod(n,price):
if n==0:
return 0
revenue=-999
for i in range(1,n+1):
##I do this, since my price[1] ie the keys to the price dictionary start from 1...n
revenue=max(revenue,price[i]+cut_rod(n-i,price))
return revenue
n=4 # print the maximum revenue we earn for rod of length 4
revenue=cut_rod(n,price)
print "revenue for rod of length %d is %d" %(n,revenue)
对于长度为 4 的杆,我在 2 和 2 上进行切割(即中间) - 我们如何记住这些索引?
编辑:我有一个大概的想法,我需要记录到目前为止看到的所有收入,以及相应的剪辑位置——但我似乎在主要通话中迷路了——我是否应该在后续通话之间存储它在 dict 结构中,稍后再查找。 我还认为索引将是一个带有“列表”作为值的字典(用于稍后查找),因为对于杆长度的某些组合 - 我们可能会切割不止一次。
+1 表示直观的解释,如果您要回答的话。
【问题讨论】:
-
这个问题似乎是题外话,因为它是关于数学的。这是一个编程网站。
-
您在math.stackexchange.com 或其兄弟姐妹中可能会有更好的运气。
标签: python-2.7 dynamic-programming mathematical-optimization memoization