大家好,我是连人。本期讲述回溯法中的最优装载问题。
以简单的语言说,就是给定两艘船,要求一批货物分别装入。
这道问题采用“先尽可能以最大载重装一艘船,再以剩下的货物装另一艘”。
这样,我们就将问题简化为了0-1背包问题。采用回溯法构建解空间,之后遍历即可。思路很简单,代码的注释我也写的很详细了。
def traceback(depth):
global n, goods, ship, best_arrange, now_arrange, best_load, now_load, remain
if depth >= n: # 遍历到叶节点,取较大值
if now_load > best_load:
best_arrange = now_arrange
best_load = now_load
return
remain -= goods[depth] # 将当前处理货物从剩余中扣去
if now_load + goods[depth] <= ship: # 如果加了这件货物没超最大载重
now_arrange[depth] =

最低0.47元/天 解锁文章
4万+





