私はこの問題を抱えています:「重量が1kgから10kgまで変化するn個のアイテムが与えられた場合、それぞれが10kgを超えない可能性があることを知って、それらを最小量のバッグにどのように分配しますか.」.
重さの大きいものから軽いものへと並べ替え、収まる場合は袋に入れ、入らない場合は新しい袋を作成することで解決しようとしました。その場合は、残りのアイテムの中で最も重いものから最も軽いものへとやり直してください。これが私のコードです:
list_of_items=raw_input("Input the items' weights (separated by spaces): ").split()
for i in range(len(list_of_items)):
list_of_items[i]=int(list_of_items[i])
list_of_items.sort()
list_of_items.reverse()
while list_of_items[0]>=10:
list_of_items=raw_input("You have input an item wheighing over 10kg: ").split()
for i in range(len(list_of_items)):
list_of_items[i]=int(list_of_items[i])
list_of_items.sort()
list_of_items.reverse()
set_of_bags=[] #In this list we'll store the bags
while(len(list_of_items)!=0):
weight=0
bag=[] #creates a new bag
for item in list_of_items: #cycle copies items to bag
if item+weight<=10:
bag.append(item)
weight+=item
set_of_bags.append(bag) #adds bag to set_of_bags
for item in bag: #deletes the items that have been put in set_of_bags from original list
list_of_items.remove(item)
# output
n=0
for bag in set_of_bags:
n+=1
weight=0
for j in bag:
weight += j
print "bag #"+str(n), bag, "=>", weight, "kg."
これで正しい答えが得られると思いますが、それを証明する方法がわかりません。何か助けはありますか?