jayati

0 - 1 Knapsack Problem

Nov 27th, 2023
1,319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  
  6. // } Driver Code Ends
  7. class Solution
  8. {
  9.     public:
  10.     //Function to return max value that can be put in knapsack of capacity W.
  11.     int knapsackUtil(int wt[], int val[], int ind, int W, vector<vector<int>>& dp) {
  12.    
  13.     if (ind == 0 || W == 0) {
  14.           return (wt[ind] <= W) ? val[0] : 0;
  15.     }
  16.  
  17.     if (dp[ind][W] != -1) {
  18.         return dp[ind][W];
  19.     }
  20.  
  21.  
  22.     int notTaken = knapsackUtil(wt, val, ind - 1, W, dp);
  23.     int taken = 0;
  24.  
  25.     if (wt[ind] <= W) {
  26.         taken = val[ind] + knapsackUtil(wt, val, ind - 1, W - wt[ind], dp);
  27.     }
  28.  
  29.  
  30.     return dp[ind][W] = max(notTaken, taken);
  31. }
  32.  
  33.     int knapSack(int W, int wt[], int val[], int n)
  34.     {
  35.         vector<vector<int>> dp(n, vector<int>(W + 1, -1));
  36.         return knapsackUtil(wt, val, n - 1, W, dp);
  37.     }
  38. };
  39.  
  40. //{ Driver Code Starts.
  41.  
  42. int main()
  43.  {
  44.     //taking total testcases
  45.     int t;
  46.     cin>>t;
  47.     while(t--)
  48.     {
  49.         //reading number of elements and weight
  50.         int n, w;
  51.         cin>>n>>w;
  52.        
  53.         int val[n];
  54.         int wt[n];
  55.        
  56.         //inserting the values
  57.         for(int i=0;i<n;i++)
  58.             cin>>val[i];
  59.        
  60.         //inserting the weights
  61.         for(int i=0;i<n;i++)
  62.             cin>>wt[i];
  63.         Solution ob;
  64.         //calling method knapSack()
  65.         cout<<ob.knapSack(w, wt, val, n)<<endl;
  66.        
  67.     }
  68.     return 0;
  69. }
  70. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment