Advertisement
Josif_tepe

Untitled

Oct 25th, 2021
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. #include <vector>
  4. #include <set>
  5. #include <map>
  6. #include <sstream>
  7. #include <cstdio>
  8. #include <algorithm>
  9. #include <stack>
  10. #include <queue>
  11. #include <cmath>
  12. #include <iomanip>
  13. #include <fstream>
  14. using namespace std;
  15. typedef long long ll;
  16. int n, w;
  17. int weight[101];
  18. int value[101];
  19. ll memo[101][100001];
  20. ll knapsack(int at, int weight_left) {
  21.     if(at == n or weight_left == 0) {
  22.         return 0;
  23.     }
  24.     if(memo[at][weight_left] != -1) {
  25.         return memo[at][weight_left];
  26.     }
  27.     ll result = 0;
  28.         result = max(result, knapsack(at + 1, weight_left));
  29.        
  30.         if(weight_left - weight[at] >= 0) {
  31.             result = max(result, knapsack(at + 1, weight_left - weight[at]) + value[at]);
  32.         }
  33.     return memo[at][weight_left] = result;
  34. }
  35. int main() {
  36.     cin >> n >> w;
  37.     for(int i = 0; i < n; i++) {
  38.         cin >> weight[i] >> value[i];
  39.     }
  40.     for(int i = 0; i < n; i++) {
  41.         for(int j = 0; j <= w; j++) {
  42.             memo[i][j] = -1;
  43.         }
  44.     }
  45.     cout << knapsack(0, w) << endl;
  46.     return 0;
  47. }
  48. /*
  49.  3 8
  50.  
  51.  3 30
  52.  4 50
  53.  5 60
  54.  knapsack(0, 8) --> max(knapsack(1, 8), knapsack(1, 8 - 3) + 30)
  55.  knapsack(1, 8) --> max(knapsack(2, 8), knapsack(2, 4) + 50)
  56.  knapsack(2, 8) --> max(knapsack(3, 8), knapsack(3, 3) + 60)
  57.  knapsack(3, 8) = 0
  58.  knapsack(3, 3) = 0
  59.  
  60.  **/
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement