使用回溯法解决0-1背包问题

  • 编程语言:Python3.9
  • 使用类库:无
  • IDE:Pycharm

使用迭代进行树的搜索,含有限界函数在每次迭代前进行判断。

result_list = []

# 运行次数
times = 0


# 判断是否可行
def workable(result: list, weight_list: list, bag: int):
    weight = 0
    for index, value in enumerate(result):
        # result中为1的项才能被计算
        if value == 1:
            weight += weight_list[index]
    if weight > bag:
        return False
    return True


# 求出最优解
def get_max_value(result_list: list, value_list: list):
    value_result = []
    for result in result_list:
        tmp_value = 0
        for index, value in enumerate(result):
            if value == 1:
                tmp_value += value_list[index]
        value_result.append(tmp_value)

    # 求出最大值
    max_value = max(value_result)

    # 求出最大值对应取法
    max_index = value_result.index(max_value)
    print(result_list[max_index])
    return max(value_result)


def main(weight_list, value_list, bag, result):
    global times
    times += 1
    # 当前物品装包
    result1 = result.copy()
    result1.append(1)
    # 判断是否可行
    if workable(result1, weight_list, bag):
        print(result1)

        # 如果完成装包,则返回,且记录
        if len(result1) == len(weight_list):
            result_list.append(result1)
            return

        main(weight_list, value_list, bag, result1)

    # 当前物品不装包
    result0 = result.copy()
    result0.append(0)
    # 判断是否可行
    if workable(result0, weight_list, bag):
        print(result0)

        # 如果完成装包,则返回,且记录
        if len(result0) == len(weight_list):
            result_list.append(result0)
            return

        main(weight_list, value_list, bag, result0)


if __name__ == '__main__':
    w = [8, 6, 4, 3]
    v = [12, 11, 9, 8]
    b = 13
    main(w, v, b, [])
    print(get_max_value(result_list, v))
    print(times)

猜你喜欢

转载自blog.csdn.net/piaolin_ying/article/details/112187078