贪婪背包算法

问题描述 投票:1回答:1

该任务是经典的背包问题。溶剂化应使用贪婪算法。我设法在下面创建代码,但是工作太慢。您能给我一个加快速度的想法吗?谢谢。

def backpack(c, array):
    array.sort(key=lambda x: x[1])
    array.sort(key=lambda x: x[0], reverse=True)
    backpack = []

    for item in array:
        if item[1] <= c:
            backpack.append(item)
            c -= item[1]

    result = []
    for item in backpack:
        result.append(item[2])
    result.sort()

    return print(*result)


c = int(input())
n = int(input())
array = list()
for i in range(n):
    item = [int(x) for x in input().split()]
    array.append(item)
    array[i].append(i)

backpack(c, array)

c是背包的重量限制。 n表示价格权重对的数量(两个数字均为int类型,而不是float)。限制如下:1)应该在权重相同的元素之间进行选择,以价格最高的元素为准。2)如果在价格相同,权重相同的元素之间进行选择,则应首先输入的元素为准。

python knapsack-problem greedy
1个回答
0
投票

我们可以使用:

def backpack(weight, arr):
    # Associate the index with each pair of the given array.
    arr = [(idx, pair) for idx, pair in enumerate(arr)]

    # sort the arr in descending order with highest price taking precedence
    arr = sorted(arr, reverse=True, key=lambda x: x[1][0]) 

    result, totalWeight = [], 0
    for item in arr:
        if item[1][1] + totalWeight <= weight:
            totalWeight += item[1][1] # increase the cummalative weight of backpack

            result.append(item[0]) # Append the index of added pair to result
    return result

示例,

arr = [[1, 2], [2, 3], [1, 1], [2, 4], [2, 3], [5, 1], [1, 5], [3, 3], [2, 2]]
weight = 7
print(backpack(weight, arr))

结果:

[5, 7, 1] # indices of pairs which are taken from array
© www.soinside.com 2019 - 2024. All rights reserved.