简体   繁体   English

背包问题(经典)

[英]knapsack problem (classic)

So I have to solve the knapsack problem for class. 所以我必须为课堂解决背包问题。 So far, I've come up with the following. 到目前为止,我已经提出了以下建议。 My comparators are functions that determine which of two subjects will be the better option (by looking at the corresponding (value,work) tuples). 我的比较器是确定两个主题中哪一个将是更好选择的函数(通过查看相应的(值,工作)元组)。

I decided to iterate over the possible subjects with work less than maxWork, and in order to find which subject is the best option at any given turn, I compared my most recent subject to all the other subjects that we have not used yet. 我决定用低于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  

The problem is I don't know why this is wrong. 问题是我不知道为什么这是错的。 I'm getting errors and I have no idea where my code is wrong (even after throwing in print statements). 我收到错误,我不知道我的代码在哪里出错(即使在抛出print语句之后)。 Help would be much appreciated, thanks! 非常感谢帮助,谢谢!

Using a simple greedy algorithm will not provide any bounds on the quality of the solution in comparison to OPT. 与OPT相比,使用简单的贪婪算法不会对解决方案的质量提供任何限制。

Here is a fully polynomial time (1 - epsilon) * OPT approximation psuedocode for knapsack: 这是一个完全多项式时间(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)

We need to define the most profitable set algorithm now. 我们现在需要定义最有利可图的集合算法。 We can do this with some dynamic programming. 我们可以通过一些动态编程实现这一点。 But first lets go over some definitions. 但首先让我们来看看一些定义。

If P is the most profitable item in the set, and n is the amount of items we have, then nP is clearly a trivial upper bound on the profit allowed. 如果P是集合中最赚钱的项目,而n是我们拥有的项目数量,那么nP显然是允许的利润的微不足道的上限。 For each i in {1,...,n} and p in {1,...,nP} we let Sip denote a subset of items whose total profit is exactly p and whose total size is minimized. 对于{1,...,n}中的每个i和{1,...,nP}中的p,我们让Sip表示项目的子集,其总利润正好为 p,其总大小最小化。 We then let A(i,p) denote the size of set Sip (infinity if it doesn't exist). 然后我们让A(i,p)表示集合Sip的大小(如果它不存在则为无穷大)。 We can easily show that A(1,p) is known for all values of p in {1,...,nP}. 我们可以很容易地证明A(1,p)对于{1,...,nP}中的所有p值都是已知的。 We will define a recurrance to compute A(i,p) which we will use as a dynamic programming problem, to return the approximate solution. 我们将定义一个计算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)

Finally we give _most_prof_set 最后我们给出_most_prof_set

def _most_prof_set(items, sizes, profit, 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) 

Source 资源

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,weight,profit          
def knapsack(m,i,weight,profit,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,weight,profit,newpr)
    return newpr
def printing_in_tabular_form(ratio,weight,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,weight,profit=sort_in_decreasing_order_of_profit(ratio,weight,profit) 
printing_in_tabular_form(ratio,weight,profit)

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

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

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