Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
C++
#include <iostream>

using namespace std;

int main()
{
    int n;
    n=8;
    int dp[n+2][n+2];
    for(int i=0;i<=n+1;i++)
        for(int j=0;j<=n+1;j++) 
            dp[i][j]=0;
    int b[]={0,1, 5, 8, 9, 10, 17, 17, 20};
    for(int i=1;i<=n+1;i++ )
        for(int j=1;j<=n+1;j++)
        {
    
            if(j>=i)
                dp[i][j]=max(dp[i-1][j],b[i]+dp[i][j-i]);
            else
                dp[i][j]=dp[i-1][j];
        }
    cout<<dp[n+1][n+1];
    return 0;
}


What I have tried:

I wanted to implement the cutting rod problem using a 2-D array.But the output given by the piece of code is different than the real output.
Guys please help me out :)
Posted
Updated 11-Dec-16 7:16am
v4
Comments
Patrice T 11-Dec-16 7:57am    
"is different than the real output" is not informative.
Show real output and actual output, explain problem.
Richard MacCutchan 11-Dec-16 8:02am    
Well it's anyone's guess what that code is supposed to do, or what really happens.
[no name] 11-Dec-16 8:15am    
Use the debugger to find out where your expected output (whatever that is) differs from the real output (whatever that is).
KarstenK 12-Dec-16 12:39pm    
This code wont compile at first. Use better variable names, braces and constants for "clean code". Maybe some more cout is helping...

1 solution

You have an out of bound array access at b[i]. The array has a size of 9 items (max. allowed index is 8) but you are accessing index 9 within your loop (last i is n+1 = 9).

I don't know the cutting rod algorithm. But you might have to either change the b array or use b[i-1].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900