Advertisement
Rakibul_Ahasan

Rod Cutting Problem (Top-Down)

Dec 25th, 2019
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int N=2001;
  4. int len;
  5. int n,temp;
  6. int cost[N];
  7.  
  8. void price(){
  9.     for(int i=1;i<=n;i++){
  10.         cin>>cost[i];
  11.     }
  12. }
  13.  
  14. int cutRod(int l){
  15.     bool done[n];
  16.     int value[n];
  17.     memset(value,0,n);
  18.     memset(done,0,n);
  19.     int max_Value=INT_MIN;
  20.  
  21.     if(l<=0) return 0;
  22.    
  23.     for(int i=1;i<=l;i++){
  24.         if(done[l-i]) {
  25.             temp=value[l-i];
  26.         }
  27.         else {
  28.             temp=cutRod(l-i);
  29.             done[l-i]=true;
  30.             value[l-i]=temp;
  31.         }
  32.    
  33.         max_Value=max (max_Value,cost[i]+temp);
  34.     }
  35.     return max_Value;
  36. }
  37.  
  38. // len<=n : YES
  39.  
  40. int main() {
  41.     cin>>len;
  42.     cin>>n;
  43.  
  44.     price();
  45.     cout<<cutRod(len);
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement