Rod cutting (DP) || C++ || EASY
21670

Rod Cutting is another term for Unbounded Knapsack
Here W becomes N , wt[ ] becoes length[ ] , val[ ] becomes price[ ]

Variation 1
In most of the questions the length[ ] is not given but only int N is given so just make an array length[ ] with values 1,2,3,4,...N
Eg this question :
Given a rod of length ‘N’ units. The rod can be cut into different sizes and each size has a cost associated with it. Determine the maximum cost obtained by cutting the rod and selling its pieces.
Solution 1) Using Bottom Up DP

int cutRod(vector<int> &price, int n)
{
	// since length array is not given therefore let us make one
    int length_cap[n];
    for(int i=1;i<=n;i++)
       length_cap[i-1]=i;
    
    // Here W->n , val[]->price[] , wt[]=>length[]
	
	// Now unbounded Knapsack as usual no changes
    int dp[n+1][n+1];
      for(int i=0;i<=n;i++)
        dp[i][0] = 0;
    
      for(int j=0;j<=n;j++)
        dp[0][j] = 0;
    
       for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(length_cap[i-1] <= j){    
              dp[i][j] = max(price[i-1] + dp[i][j-length_cap[i-1]], 
                             dp[i-1][j]);
            }
            else
                dp[i][j] = dp[i-1][j];
        }
    }
    return dp[n][n];
}

Solution 2) using Top Down Dp

int cutRodUtil(vector<int> &price, int maxLen, int n, vector<vector<int>> &cost)
{
    // Base condition.
    if (n <= 0 || maxLen <= 0)
    {
        return 0;
    }

    // Checks whether problem is already calculated or not.
    if (cost[n][maxLen] != -1)
    {
        return cost[n][maxLen];
    }

    /*
       If the length of the rod to be cut is less than or equal
       to the size of rod of length 'max_len',
       then depending on profit, either it will accept the cut or discard it.
    */
    if (n <= maxLen)
    {
        cost[n][maxLen] = max(price[n - 1] + cutRodUtil(price, maxLen - n, n, cost), cutRodUtil(price, maxLen, n - 1, cost));
    }

    /*
       If the length of the rod to be cut is
       greater than the size of rod of length
       'max_len', cutting is not permitted.
    */
    else
    {
        cost[n][maxLen] = cutRodUtil(price, maxLen, n - 1, cost);
    }

    return cost[n][maxLen];
}

int cutRod(vector<int> &price, int n)
{
    // Two state dp to store the sub-problems.
    vector<vector<int>> cost(n + 2, vector<int>(n + 2, -1));
    
    return cutRodUtil(price, n, n, cost);
}

Easy recursion
image
Easy Memo
image
Easy DP
image

Comments (8)