Advertisement
Guest User

dpVector

a guest
Nov 19th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4.  
  5. int n,capacity;
  6. std::vector<int>wt,val;
  7. int dp[2][10001];
  8.  
  9. void read(){
  10.  
  11.     std::cin >> n >> capacity;
  12.  
  13.     wt.resize(n + 1);
  14.     val.resize(n + 1);
  15.  
  16.     for(int i = 1;i <= n;i++)
  17.         std::cin >> wt[i] >> val[i];
  18. }
  19.  
  20. void precalc(){
  21.  
  22.     for(int i = 1;i <= n;i++){
  23.         int index = (i % 2 == 0 ? 0 : 1);
  24.         for(int j = 1;j <= capacity;j++){
  25.             if(index == 0){// if i is an even nr
  26.                 if(j < wt[i])
  27.                     dp[0][j] = dp[1][j];
  28.                 else
  29.                     dp[0][j] = std::max(dp[1][j],dp[1][j - wt[i]] + val[i]);
  30.             }else{
  31.                 if(j < wt[i])
  32.                     dp[1][j] = dp[0][j];
  33.                 else
  34.                     dp[1][j] = std::max(dp[0][j],dp[0][j - wt[i]] + val[i]);
  35.             }
  36.         }
  37.     }
  38. }
  39.  
  40. void print(){
  41.     if(n % 2 == 0)
  42.         std::cout << dp[0][capacity];
  43.     else
  44.         std::cout << dp[1][capacity];
  45. }
  46.  
  47. int main(){
  48.  
  49.     read();
  50.     precalc();
  51.     print();
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement