任务是经典的背包问题。溶剂化应使用贪婪算法。我设法在下面创建代码,但是工作太慢。您能给我一个加快速度的想法吗?谢谢。
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)在价格相同,权重相同的元素之间进行选择,应以先输入的元素为准。
答案 0 :(得分:1)
我们可以使用:
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
答案 1 :(得分:0)
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)