Advertisement
amu2002

0/1Knapsack

Nov 20th, 2023 (edited)
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. n = int(input("Enter no. of items: "))
  2. maxwt = int(input("Maximum weight: "))
  3. profits = list(map(int, input("Enter profit value of items: ").split()))
  4. weights = list(map(int, input("Enter weight of items: ").split()))
  5.  
  6. def knapsack_dp_branch_bound(n, maxwt, profits, weights):
  7.     dp = [[0 for _ in range(maxwt + 1)] for _ in range(n + 1)]
  8.  
  9.     pq = []
  10.  
  11.     pq.append((0, 0, 0, 0))
  12.  
  13.     max_profit = 0
  14.  
  15.     while pq:
  16.         items, weight, profit, bound = pq.pop()
  17.  
  18.         if weight > maxwt:
  19.             continue
  20.  
  21.         if profit > max_profit:
  22.             max_profit = profit
  23.  
  24.         if items == n:
  25.             continue
  26.  
  27.         item_weight = weights[items]
  28.         item_profit = profits[items]
  29.  
  30.         remaining_weight = maxwt - weight
  31.         upper_bound = profit + bound
  32.  
  33.         if weight + item_weight <= maxwt:
  34.             pq.append((items + 1, weight + item_weight, profit + item_profit, upper_bound))
  35.  
  36.         bound = upper_bound - (profit - item_profit) * (remaining_weight / item_weight)
  37.  
  38.         if bound > max_profit:
  39.             pq.append((items + 1, weight, profit, bound))
  40.  
  41.     return max_profit
  42.  
  43. print("Item\tProfit\tBranch & Bound")
  44. for i in range(n):
  45.     profit_i = knapsack_dp_branch_bound(i + 1, maxwt, profits[:i + 1], weights[:i + 1])
  46.     print(f"{i + 1}\t{profits[i]}\t{profit_i}")
  47.  
  48. """
  49. Enter no. of items: 5
  50. Maximum weight: 10  
  51. Enter profit value of items: 10 15 10 12 8
  52. Enter weight of items: 3 3 2 5 1
  53. Item    Profit  Branch & Bound
  54. 1       10      10
  55. 2       15      25
  56. 3       10      35
  57. 4       12      37
  58. 5       8       43
  59. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement