用于切割棒的Python程序 | DP-13
给定一根长度为 n 英寸的杆和一个价格数组,其中包含所有尺寸小于 n 的块的价格。确定通过切割杆并出售碎片可获得的最大值。例如,如果杆的长度为 8,并且不同部分的值如下所示,则最大可获得值为 22(通过切割长度为 2 和 6 的两根)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 1 5 8 9 10 17 17 20
如果价格如下,那么最大可获得值为24(通过切割8块长度1)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 3 5 8 9 10 17 17 20
以下是棒切割问题的简单递归实现。实现简单地遵循上面提到的递归结构。
Python3
# A Naive recursive solution
# for Rod cutting problem
import sys
# A utility function to get the
# maximum of two integers
def max(a, b):
return a if (a > b) else b
# Returns the best obtainable price for a rod of length n
# and price[] as prices of different pieces
def cutRod(price, n):
if(n <= 0):
return 0
max_val = -sys.maxsize-1
# Recursively cut the rod in different pieces
# and compare different configurations
for i in range(0, n):
max_val = max(max_val, price[i] +
cutRod(price, n - i - 1))
return max_val
# Driver code
arr = [1, 5, 8, 9, 10, 17, 17, 20]
size = len(arr)
print("Maximum Obtainable Value is", cutRod(arr, size))
# This code is contributed by 'Smitha Dinesh Semwal'
Python3
# A Dynamic Programming solution for Rod cutting problem
INT_MIN = -32767
# Returns the best obtainable price for a rod of length n and
# price[] as prices of different pieces
def cutRod(price, n):
val = [0 for x in range(n + 1)]
val[0] = 0
# Build the table val[] in bottom up manner and return
# the last entry from the table
for i in range(1, n + 1):
max_val = INT_MIN
for j in range(i):
max_val = max(max_val, price[j] + val[i-j-1])
val[i] = max_val
return val[n]
# Driver program to test above functions
arr = [1, 5, 8, 9, 10, 17, 17, 20]
size = len(arr)
print("Maximum Obtainable Value is " + str(cutRod(arr, size)))
# This code is contributed by Bhavya Jain
输出:
Maximum Obtainable Value is 22
考虑到上述实现,以下是长度为 4 的 Rod 的递归树。
cR() ---> cutRod()
cR(4)
/ /
/ /
cR(3) cR(2) cR(1) cR(0)
/ | / |
/ | / |
cR(2) cR(1) cR(0) cR(1) cR(0) cR(0)
/ | |
/ | |
cR(1) cR(0) cR(0) cR(0)
/
/
CR(0)
在上面的部分递归树中,cR(2) 被求解了两次。我们可以看到有很多子问题被一次又一次地解决。由于再次调用相同的子问题,此问题具有重叠子问题属性。因此,Rod Cutting 问题具有动态规划问题的两个属性(参见 this 和 this)。与其他典型的动态规划(DP)问题一样,通过以自下而上的方式构造临时数组 val[] 可以避免重复计算相同的子问题。
Python3
# A Dynamic Programming solution for Rod cutting problem
INT_MIN = -32767
# Returns the best obtainable price for a rod of length n and
# price[] as prices of different pieces
def cutRod(price, n):
val = [0 for x in range(n + 1)]
val[0] = 0
# Build the table val[] in bottom up manner and return
# the last entry from the table
for i in range(1, n + 1):
max_val = INT_MIN
for j in range(i):
max_val = max(max_val, price[j] + val[i-j-1])
val[i] = max_val
return val[n]
# Driver program to test above functions
arr = [1, 5, 8, 9, 10, 17, 17, 20]
size = len(arr)
print("Maximum Obtainable Value is " + str(cutRod(arr, size)))
# This code is contributed by Bhavya Jain
输出:
Maximum Obtainable Value is 22
请参阅有关切割棒的完整文章 | DP-13 了解更多详情!