Advertisement
Fastrail08

01Knapsack

May 19th, 2025
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int solveKnapSack(int index, int profit, int maxW, vector<int> &items, vector<int> &weight, int &max_profit, vector<vector<int> > &memo){
  5.     if(index >= items.size()){
  6.         max_profit = max(max_profit, profit);
  7.         return 0;
  8.     }
  9.     if(memo[index][maxW] != INT_MIN){
  10.         return memo[index][maxW];
  11.     }
  12.     int itemInc = 0, itemExc = 0;
  13.     // item in subset, only if currW + weight[index] <= w
  14.     if(maxW - weight[index] >= 0){
  15.         itemInc += items[index] + solveKnapSack(index + 1, profit + items[index], maxW - weight[index], items, weight, max_profit, memo);
  16.     }
  17.    
  18.     // item not in subset
  19.     itemExc = solveKnapSack(index + 1, profit, maxW, items, weight, max_profit, memo);
  20.     return memo[index][maxW] = max(itemInc, itemExc);
  21. }
  22.  
  23.  
  24. int solveKnapSackDP(vector<int> &items, vector<int> &weight, int &maxW){
  25.     vector<vector<int> > dp(items.size(), vector<int> (maxW + 1, -1));
  26.     // the first column has wt = 0, so no item can be included, hence profit = 0
  27.     for(int i = 0; i < items.size(); i++){
  28.         dp[i][0] = 0;
  29.     }
  30.    
  31.     for(int j = 1; j <= maxW; j++){
  32.         dp[0][j] = j < weight[0] ? 0 : items[0];
  33.     }
  34.    
  35.     for(int i = 1; i < items.size(); i++){
  36.         for(int j = 1; j <= maxW; j++){
  37.             dp[i][j] = j < weight[i] ? dp[i - 1][j] : max(dp[i - 1][j], items[i] + dp[i - 1][j - weight[i]]);
  38.         }
  39.     }
  40.     return dp[items.size() - 1][maxW];
  41. }
  42.  
  43. int main() {
  44.     // your code goes here
  45.     int n, maxW;
  46.     cin >> n;
  47.     vector<int> items(n), weight(n);
  48.     for(int i = 0; i < n; i++){
  49.         cin >> items[i];
  50.     }
  51.     for(int i = 0; i < n; i++){
  52.         cin >> weight[i];
  53.     }
  54.     cin >> maxW;
  55.     int max_profit = INT_MIN;
  56.     vector<vector<int> > memo(n, vector<int>(maxW + 1, INT_MIN));
  57.    
  58.     //memo call (return method)
  59.     //cout << max(solveKnapSack(0, 0, maxW, items, weight, max_profit, memo), 0) << '\n';
  60.    
  61.     //(print method)
  62.     /*
  63.      print max(max_profit, 0), as the min value can be 0 when no items were included
  64.      cout << max(max_profit, 0) << '\n';
  65.      */
  66.    
  67.     //dp call
  68.     cout << solveKnapSackDP(items, weight, maxW) << '\n';
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement