First, the knapsack problem
1. Description of the problem
2, the introduction of dynamic programming table to explain the problem
This table
Backpack capacity: maximum input is given,
Item number: 0, 0 indicates the best combination of the first article;
1, 1 indicates the best combination of the first item; (so there is not a certain number of items requested order ??)
2, represents the best combination of the first two items;
The best combination of value can be derived: Blank grid
3, dynamic programming to fill out the form value data
a, item number is 0, the first 0 items combined (no items), no matter how much capacity backpack, valued at zero.
B, knapsack capacity is 0, the article can not pretend to be, the value of 0
C, a capacity of a knapsack, Item No. 1:
(1) No. 1 if fitted items, the value of change;
(2) If you do not install the 1st item, the value 0 and the value of goods before think the same;
Since the fit article 1, only select all (2)
d, backpack capacity of 2, items numbered 1:
(1) determine the current capacity of the backpack can fit in the current article; can
(2) if: the judge hold that the total value of goods and do not install the item total value of the larger
If you can not: do not install this item, the total value and the total value is equal to the previous line
d, backpack capacity of 3, item number 2 is: (1) determine the current capacity of the backpack can fit in the current article; can
(2) if: the judging means after the total value of the article (4) is not installed and the total value of the item (3) which is larger
If you can not: do not install this item, the total value and the total value is equal to the previous line
Finally, taking the total value of 4 large
e, other blank and so on, not detailed. . . .
Code:
1, the data input:
n = int(input()) w = list(map(int,input().split())) v = list(map(int,input().split())) c = int(input()) """ 测试数据: n = 4 物品的数量, w = [2, 3, 4, 5] 每个物品的重量, v = [3,4, 5, 6 ] 每个物品的价值, c = 8 书包能承受的重量, """
2、动态规划表的绘制
value = [[0 for j in range(c + 1)] for i in range(n + 1)] #构造一个dp表 for i in range(1, n + 1): for j in range(1, c + 1): if (w[i-1]>j): #如果当前物品质量大于当前背包容量 value[i][j] = value[i-1][j] #不装改物品,总价值和前一个总价值相等 else: #如果可以装下该物品,比较 不装该物品的价值 和 装下该物品后的价值那个更大,取大值。 value[i][j] = max(value[i-1][j],value[i-1][j-w[i-1]]+v[i-1]) for x in value: print(x)
4、背包问题回溯
理解:根据动态规划表的构建,如果当前物品被放入背包中,则当前总价值大于前一行的总价值。
所以可以根据两行总价值 来判断 当前物品是否在背包中。
代码实现:
print('最大价值为:', value[n][c]) x = [False for i in range(n)] j = c for i in range(n, 0, -1): if value[i][j] > value[i - 1][j]: #判断当前价值与前一行的价值 x[i - 1] = True #当前物品置一 j -= w[i - 1] #背包容量里面减去相应的物品容量 print('背包中所装物品为:') for i in range(n): if x[i]: print('第', i+1, '个,', end='')