所以我在python中有这个代码,目前它只返回切割杆的最大值。我该如何修改它还能给我切割的位置?它需要一个价格清单,其中指数+ 1对应于每个长度上的杆的值,n为杆的长度。
问题:http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html
def cutRod(price, n):
val = [0 for x in range(n+1)]
val[0] = 0
for i in range(1, n+1):
max_val = 0
for j in range(i):
max_val = max(max_val, price[j] + val[i-j-1])
val[i] = max_val
return val[n]
答案 0 :(得分:0)
如果这是问题: Rod cutting
假设代码工作正常,您将不得不添加一个条件而不是Max操作来检查两个中的哪一个被选中并将其推送到数组中:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
答案 1 :(得分:0)
我知道这很旧,但是以防万一有人看到我...我实际上只是在看这个问题。我认为问题在于处理索引时这些dp问题可能会很棘手。先前的答案不会仅仅因为需要调整此行而正确打印解决方案...
cur_max_index = j
应该是cur_max_index = j + 1
其余...
def cut_rod(prices, length):
values = [0] * (length + 1)
cuts = [-1] * (length + 1)
max_val = -1
for i in range(1, length + 1):
for j in range(i):
temp = prices[j] + values[i - j - 1]
if temp > max_val:
max_val = prices[j] + values[i - j - 1]
cuts[i] = j + 1
values[i] = max_val
return values[length], cuts
def print_cuts(cuts, length):
while length > 0:
print(cuts[length], end=" ")
length -= cuts[length]
max_value, cuts = cut_rod(prices, length)
print(max_value)
print_cuts(cuts, length)