CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Threaded View

  1. #1
    Join Date
    Feb 2022
    Posts
    11

    Basic Dynamic Programming code

    Hello
    i'm just trying to do some basic example of dynamic programming and i've an issue with the following code:

    Code:
    #include <cstdio>
    #include <vector>
    #include <ctime>
    using namespace std;
    
    int cut_rod(vector<int>p,int l){
      int m;
      if (l==0) return 0;
      int q=-32768;
      for (int i=1;i<=p.size();i++){
        if ((l-i)<0) continue;
        m=p[i-1]+cut_rod(p,l-i);
        if (q<m) q=m;
      }
    return q;
    }
    
    int main(){
      int n,t;
      int tstart;
      int tend;
      tstart=clock();
      scanf("%i %i\n ",&n,&t);
      int q;
      int l;
      vector<int> p;
      
        for (int j=0;j<n;j++){
          p.push_back(0);
          scanf("%i",&p[j]);
        }
      for (int i=0;i<t;t++){
        scanf("%i",&l);
        q=cut_rod(p,l);
        printf("Case %i: %i \n",i,q);
    
      }
      tend=clock();
      printf("Elapsed time : %i",tend-tstart);
      return 0;
    }
    The program go crazy also for examples with few iteration like:

    Code:
    2 1
    3 4
    3
    What's the problem?
    Last edited by Quasar999; March 26th, 2022 at 10:03 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured