背包问题经典

问题描述

| 因此,我必须在上课时解决背包问题。到目前为止,我已经提出了以下建议。我的比较器是确定两个主题中哪个主题更好的函数(通过查看相应的(值,工作)元组)。 我决定对工作量小于maxWork的可能主题进行迭代,为了找出在任何给定回合中哪个主题是最佳选择,我将最近的主题与我们尚未使用的所有其他主题进行了比较。
def greedyAdvisor(subjects,maxWork,comparator):
    \"\"\"
    Returns a dictionary mapping subject name to (value,work) which includes
    subjects selected by the algorithm,such that the total work of subjects in
    the dictionary is not greater than maxWork.  The subjects are chosen using
    a greedy algorithm.  The subjects dictionary should not be mutated.

    subjects: dictionary mapping subject name to (value,work)
    maxWork: int >= 0
    comparator: function taking two tuples and returning a bool
    returns: dictionary mapping subject name to (value,work)
    \"\"\"

    optimal = {}
    while maxWork > 0:
        new_subjects = dict((k,v) for k,v in subjects.items() if v[1] < maxWork)
        key_list = new_subjects.keys()
        for name in new_subjects:
            #create a truncated dictionary
            new_subjects = dict((name,new_subjects.get(name)) for name in key_list)
            key_list.remove(name)
            #compare over the entire dictionary
            if reduce(comparator,new_subjects.values())==True:
                #insert this name into the optimal dictionary
                optimal[name] = new_subjects[name]
                #update maxWork
                maxWork = maxWork - subjects[name][1]
                #and restart the while loop with maxWork updated
                break
    return optimal  
问题是我不知道为什么这是错误的。我遇到了错误,而且我不知道我的代码在哪里出错(即使在抛出print语句之后)。帮助将不胜感激,谢谢!     

解决方法

与OPT相比,使用简单的贪心算法不会对解决方案的质量提供任何限制。 这是一个完整的多项式时间(1-epsilon)*背包的OPT近似伪代码:
items = [...]  # items
profit = {...} # this needs to be the profit for each item
sizes = {...}  # this needs to be the sizes of each item
epsilon = 0.1  # you can adjust this to be arbitrarily small
P = max(items) # maximum profit of the list of items
K = (epsilon * P) / float(len(items))
for item in items:
    profit[item] = math.floor(profit[item] / K)
return _most_prof_set(items,sizes,profit,P)
现在,我们需要定义最有利可图的集合算法。我们可以通过一些动态编程来做到这一点。但是首先让我们回顾一些定义。 如果P是集合中最赚钱的商品,而n是我们拥有的商品数量,那么nP显然是允许利润的微不足道的上限。对于{1,...,n}中的每个i和{1,...,nP}中的p,我们让Sip表示总利润恰好为p并且总大小最小的项的子集。然后,让A(i,p)表示集合Sip的大小(如果不存在,则为无穷大)。我们可以很容易地证明,{1,...,nP}中p的所有值都已知A(1,p)。我们将定义一个递归来计算A(i,p),并将其用作动态规划问题,以返回近似解。
A(i + 1,p) = min {A(i,p),size(item at i + 1 position) + A(i,p - profit(item at i + 1 position))} if profit(item at i + 1) < p otherwise A(i,p)
最后,我们给出_most_prof_set
def _most_prof_set(items,P):
    A = {...}
    for i in range(len(items) - 1):
        item = items[i+1]
        oitem = items[i]
        for p in [P * k for k in range(1,i+1)]:
            if profit[item] < p:
                A[(item,p)] = min([A[(oitem,p)],\\
                                     sizes[item] + A[(item,p - profit[item])]])
            else:
                A[(item,p)] = A[(oitem,p)] if (oitem,p) in A else sys.maxint
    return max(A) 
资源     ,
def swap(a,b):
    return b,a

def sort_in_decreasing_order_of_profit(ratio,weight,profit):
    for i in range(0,len(weight)):
        for j in range(i+1,len(weight)) :
            if(ratio[i]<ratio[j]):
                ratio[i],ratio[j]=swap(ratio[i],ratio[j])
                weight[i],weight[j]=swap(weight[i],weight[j])
                profit[i],profit[j]=swap(profit[i],profit[j])
    return ratio,profit          
def knapsack(m,i,newpr):

    if(i<len(weight) and m>0):
        if(m>weight[i]):
            newpr+=profit[i]
        else:
            newpr+=(m/weight[i])*profit[i]  
        newpr=knapsack(m-weight[i],i+1,newpr)
    return newpr
def printing_in_tabular_form(ratio,profit):

    print(\" WEIGHT\\tPROFIT\\t RATIO\")
    for i in range(0,len(ratio)):
        print (\'{}\\t{} \\t {}\'.format(weight[i],profit[i],ratio[i]))

weight=[10.0,10.0,18.0]
profit=[24.0,15.0,25.0]
ratio=[]
for i in range(0,len(weight)):
    ratio.append((profit[i])/weight[i])
#caling function
ratio,profit=sort_in_decreasing_order_of_profit(ratio,profit) 
printing_in_tabular_form(ratio,profit)

newpr=0
newpr=knapsack(20.0,newpr)          
print(\"Profit earned=\",newpr)