简体   繁体   中英

0-1 Knapsack problem with bound in the number of items

I have a list with the weight, value and number of copies available of the items in a shop in the form [w_i, v_i, c_i]. I can not carry more than W weight with me, that is why I need to optimize my decision. How many copies of what item I should take? And, what is the max value I can generate with this selection?

This is a variant of 0-1 Knapsack problem. I have the solution for traditional problem here. But How can I modify this code for my desired solution?

    n=len(val)
    table = [[0 for x in range(W + 1)] for x in range(n + 1)] 
 
    for i in range(n + 1): 
        for j in range(W + 1): 
            if i == 0 or j == 0: 
                table[i][j] = 0
            elif wt[i-1] <= j: 
                table[i][j] = max(val[i-1] + table[i-1][j-wt[i-1]], table[i-1][j]) 
            else: 
                table[i][j] = table[i-1][j] 
   
    return table[n][W]  

With nb being the number of copies available for each item:

occ_max = max(nb)
n= len(val)
table = [[[0]*(occ_max+1) for x in range(W + 1)] for x in range(n + 1)]
for i in range(n + 1): 
    for j in range(W + 1):
        if i == 0:
            table[i][j][0] = 0
        else:
            for k in range(nb[i-1], -1, -1):
                if k == nb[i-1] or wt[i-1] > j:
                    table[i][j][k] = table[i-1][j][0]
                else:
                    table[i][j][k] = max(val[i-1] + table[i][j-wt[i-1]][k+1], table[i-1][j][0])
table[n][W][0]

Basically, k is the number of elements of type i-1 you have taken. On a given (i,j,k), you choose whether the best answer is to take one more element of type i-1, which is table[i][j][k+1] or to stop taking elements of type index-1 and start looking at elements of type i-2, which is table[i-1][j][0].

Also, I removed the if j == 0 in case of elements without weight.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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