繁体   English   中英

贪心背包算法

[英]Greedy knapsack algorithm

该任务是经典的背包问题。 求解时应使用贪心算法。 我设法在下面创建了代码,但它工作得太慢了。 你能告诉我如何加快速度吗? 谢谢你。

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)如果您在相同价格和相同重量的元素之间进行选择,则应取最先输入的元素。

我们可以用:

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 contains the pairs of <price, weight>
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 in arr which are taken from array and added to backpack
def backpack(c, array):
    array.sort(key=lambda x: x[2], reverse=True)
    print(array)
    result = 0
    for item in array:
        if c-item[1] >= 0:
            c=c-item[1]
            result=result+item[0]
        else:
            fraction = c/float(item[1])
            print(fraction)
            result+=(item[0]*fraction)
            break

    return result


c = int(input())
n = int(input())
array = []
for i in range(n):
    item = tuple(int(x) for x in raw_input().split())
    array.append(item+(item[0]//item[1],))
backpack(c, array)

暂无
暂无

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

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