Advertisement
Matteogoli

zaino.cpp

Mar 1st, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. const int DIM = 100000;
  6. const int INF = 100000;
  7.  
  8. int V[DIM], P[DIM];
  9. long long int ** DP;
  10.  
  11. long long int zaino(int n, int C);
  12. long long int zainoRec(int i, int C);
  13.  
  14. int main(){
  15.     ifstream in("input.txt");
  16.     ofstream out("output.txt");
  17.    
  18.     int c, n;
  19.    
  20.     in >> c >> n;
  21.    
  22.     for(int i = 0; i < n; i++){
  23.         in >> P[i] >> V[i];
  24.         cout << P[i] << " " << V[i] << endl;
  25.     }
  26.    
  27.     long long int res = zaino(n, c);
  28.    
  29.     cout << res << endl;
  30.     out << res;
  31.    
  32.     return 0;
  33. }
  34.  
  35. long long int max(long long int a, long long int b){
  36.     return (a > b) ? a : b;
  37. }
  38.  
  39. long long int zaino(int n, int C){
  40.     DP = new long long int *[n];
  41.     for(int i = 0; i < n; i++)
  42.         DP[i] = new long long int [C];
  43.    
  44.     for(int i = 0; i < n; i++){
  45.         for(int j = 0; j < C; j++)
  46.             DP[i][j] = -1;
  47.     }
  48.     return zainoRec(n, C);
  49. }
  50.  
  51. long long int zainoRec(int i, int C){
  52.     if(C == 0 || i == 0){
  53.         return 0;
  54.     } else if (C < 0) {
  55.         return -INF;
  56.     }
  57.    
  58.     if(DP[i][C] < 0){
  59.         int notTaken = zainoRec(i-1, C);
  60.         int taken = V[i] + zainoRec(i-1, C-P[i]);
  61.         DP[i][C] = max(notTaken, taken);
  62.     }
  63.     cout << "i= " << i << ", C= " << C << " --> " << DP[i][C] << endl;
  64.     return DP[i][C];
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement