ishanra

Untitled

May 9th, 2021
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. /* A Naive recursive implementation of
  2. 0-1 Knapsack problem */
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // A utility function that returns
  7. // maximum of two integers
  8. int max(int a, int b) { return (a > b) ? a : b; }
  9.  
  10. // Returns the maximum value that
  11. // can be put in a knapsack of capacity W
  12. int knapSack(int W, vector<int> &wt, vector<int> val, int N)
  13. {
  14.  
  15.     // Base Case
  16.     if (n == 0 || W == 0)
  17.         return 0;
  18.  
  19.     // If weight of the nth item is more
  20.     // than Knapsack capacity W, then
  21.     // this item cannot be included
  22.     // in the optimal solution
  23.     if (wt[n - 1] > W)
  24.         return knapSack(W, wt, val, n - 1);
  25.  
  26.     // Return the maximum of two cases:
  27.     // (1) nth item included
  28.     // (2) not included
  29.     else
  30.         return max(
  31.             val[n - 1]
  32.                 + knapSack(W - wt[n - 1],
  33.                         wt, val, n - 1),
  34.             knapSack(W, wt, val, n - 1));
  35. }
  36.  
  37. // Driver code
  38. int main()
  39. {  
  40.     int N,W;
  41.     cin>>N>>W;
  42.     vector<int>wt(N),val(N);
  43.     for(int i=0;i<N;i++)
  44.     {
  45.         cin>>wt[i];
  46.     }
  47.     for(int i=0;i<N;i++)
  48.     {
  49.         cin>>val[i];
  50.     }
  51.     cout << knapSack(W, wt, val, N);
  52.     return 0;
  53. }
  54.  
  55. // This code is contributed by rathbhupendra
  56.  
Advertisement
Add Comment
Please, Sign In to add comment