Guest User

Untitled

a guest
Oct 18th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. #### unbounded knapsack: similar to 01 knapsack but we can choose infinite number of items
  2. #### example w=[2 3 4], value=[100,50,10],; in 01 knapsack, w=2 can be picked one time,
  3. #### but in unbounded, we can pick multiple times.
  4. def unboundKS(C,w,v):
  5. m=len(w)
  6. L=[[0]*(C+1) for x in range(0,m+1)] ## due to the base case get the first row and column, then the matrix size should be +1 compare with the real data is C and m
  7.  
  8. for i in range(0,m+1):
  9. for j in range(0,C+1):
  10. ### base cases:
  11. if i==0 or j==0:
  12. L[i][j]=0
  13. if w[i-1]>j:
  14. L[i][j]=L[i-1][j]
  15. else:
  16. k=j//w[i-1]
  17. maximum=0
  18. for q in range(0,k+1):
  19. maximum=max(q*v[i-1]+L[i-1][j-q*w[i-1]],maximum) ## scan all posible of q which is the number of item [i-1]th be picked
  20. L[i][j]=maximum
  21. return L[m][C]
  22. C=100
  23. v=[10,30,20]
  24. w=[5,10,15]
  25. print(unboundKS(C,w,v))
Add Comment
Please, Sign In to add comment