繁体   English   中英

我使用回溯在 python 中为 0/1 背包问题弄错了 output

[英]I got wrong output for 0/1 knapsack problem in python using backtracking

我用回溯技术实现了0/1背包问题,但是没有得到预期的结果。

  • capacity : 背包总容量
  • cargo_number : 物品数量
  • size : 每件物品的重量
  • profit : 每个项目的利润

测试用例 1:

输入

16

4

2 5 10 5

40 30 50 10 

output

90 (correct result)

测试案例2:

输入

10

5

7 2 10 2 4

46 19 30 49 11

输出

98 (wrong result, expected result is 95.)
from typing import List


class Solution:
    def fractional_knapsack(self, n: int, size: List[int], profit: List[int], left_capacity: int):
        if left_capacity <= 0:
            return 0
        # sort profit and size in descending order
        sorted_index = sorted(range(n), key=lambda i: profit[i] / size[i], reverse=True)
        sorted_size = [size[i] for i in sorted_index]
        sorted_profit = [profit[i] for i in sorted_index]

        estimated_profit = 0
        for i in range(n):
            if sorted_size[i] <= left_capacity:
                estimated_profit += sorted_profit[i]
                left_capacity -= sorted_size[i]
            else:
                estimated_profit += sorted_profit[i] * (left_capacity / sorted_size[i])
                break
        return estimated_profit

    def knapsack(self, i, left_capacity):
        global max_profit
        if i >= cargo_number or left_capacity <= 0:
            return

        current_s = sum(size[i] for i in range(cargo_number) if x[i] == 1)  # sum of current size
        current_p = sum(profit[i] for i in range(cargo_number) if x[i] == 1)  # sum of current profit

        if current_s + size[i] <= left_capacity:
            estimated_profit = self.fractional_knapsack(
                cargo_number - (i + 1),
                size[i + 1:],
                profit[i + 1:],
                left_capacity - size[i],
            )
            if current_p + profit[i] > max_profit:  # renew max_profit
                max_profit = current_p + profit[i]
            x[i] = 1  # if item is selected
            self.knapsack(i + 1, left_capacity - size[i])  #

        estimated_profit = fractional_knapsack(
        cargo_number - (i + 1), size[i + 1:], profit[i + 1:], left_capacity
    )
        if current_p + estimated_profit > max_profit:
            x[i] = 0  # if item is not selected
            self.knapsack(i + 1, left_capacity)


capacity = int(input())
cargo_number = int(input())
size = list(map(int, input().split()))
profit = list(map(int, input().split()))

x = [0] * cargo_number  # if x[i] == 1, then i-th item is selected, otherwise not
max_profit = 0

solution = Solution()
solution.knapsack(0, capacity)
print(max_profit)

我用state空间树解决了。 如何修改代码以通过测试用例 2?

可能还有其他问题,但我发现了一个错误:

if current_s + size[i] <= left_capacity:

应该:

if size[i] <= left_capacity:

capacity_left是为新项目计算的,但current_s是为已经存在的项目计算的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM