Dynamic Programming | Set 13 (Cutting a Rod)
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)
length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 1 5 8 9 10 17 17 20
And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1)
length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 3 5 8 9 10 17 17 20
The naive solution for this problem is to generate all configurations of different pieces and find the highest priced configuration. This solution is exponential in term of time complexity. Let us see how this problem possesses both important properties of a Dynamic Programming (DP) Problem and can efficiently solved using Dynamic Programming.
1) Optimal Substructure:
We can get the best price by making a cut at different positions and comparing the values obtained after a cut. We can recursively call the same function for a piece obtained after a cut.
Let cutRoad(n) be the required (best possible price) value for a rod of lenght n. cutRod(n) can be written as following.
cutRod(n) = max(price[i] + cutRod(n-i-1)) for all i in {0, 1 .. n-1}
2) Overlapping Subproblems
Following is simple recursive implementation of the Rod Cutting problem. The implementation simply follows the recursive structure mentioned above.
// A Naive recursive solution for Rod cutting problem
#include<stdio.h>
#include<limits.h>
// A utility function to get the maximum of two integers
int max(int a, int b) { return (a > b)? a : b;}
/* Returns the best obtainable price for a rod of length n and
price[] as prices of different pieces */
int cutRod(int price[], int n)
{
if (n <= 0)
return 0;
int max_val = INT_MIN;
// Recursively cut the rod in different pieces and compare different
// configurations
for (int i = 0; i<n; i++)
max_val = max(max_val, price[i] + cutRod(price, n-i-1));
return max_val;
}
/* Driver program to test above functions */
int main()
{
int arr[] = {1, 5, 8, 9, 10, 17, 17, 20};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Maximum Obtainable Value is %d\n", cutRod(arr, size));
getchar();
return 0;
}
Output:
Maximum Obtainable Value is 22
Considering the above implementation, following is recursion tree for a Rod of length 4.
cR() ---> cutRod()
cR(4)
/ / \ \
/ / \ \
cR(3) cR(2) cR(1) cR(0)
/ | \ / \ |
/ | \ / \ |
cR(2) cR(1) cR(0) cR(1) cR(0) cR(0)
/ \ | |
/ \ | |
cR(1) cR(0) cR(0) cR(0)
In the above partial recursion tree, cR(2) is being solved twice. We can see that there are many subproblems which are solved again and again. Since same suproblems are called again, this problem has Overlapping Subprolems property. So the Rod Cutting problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array val[] in bottom up manner.
// A Dynamic Programming solution for Rod cutting problem
#include<stdio.h>
#include<limits.h>
// A utility function to get the maximum of two integers
int max(int a, int b) { return (a > b)? a : b;}
/* Returns the best obtainable price for a rod of length n and
price[] as prices of different pieces */
int cutRod(int price[], int n)
{
int val[n+1];
val[0] = 0;
int i, j;
// Build the table val[] in bottom up manner and return the last entry
// from the table
for (i = 1; i<=n; i++)
{
int max_val = INT_MIN;
for (j = 0; j < i; j++)
max_val = max(max_val, price[j] + val[i-j-1]);
val[i] = max_val;
}
return val[n];
}
/* Driver program to test above functions */
int main()
{
int arr[] = {1, 5, 8, 9, 10, 17, 17, 20};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Maximum Obtainable Value is %d\n", cutRod(arr, size));
getchar();
return 0;
}
Output:
Maximum Obtainable Value is 22
Time Complexity of the above implementation is O(n^2) which is much better than the worst case time complexity of Naive Recursive implementation.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
u can see a video explanation of the algorithm on the link below
http://www.youtube.com/watch?v=U-09Gs6cbsQ
/* Returns the best obtainable price for a rod of length n and
price[] as prices of different pieces */
int cutRod(int price[], int n)
{
if (n <= 0)
return 0;
int max_val = INT_MIN;
// Recursively cut the rod in different pieces and compare different
// configurations
for (int i = 0; i<n; i++)
max_val = max(max_val, price[i] + cutRod(price+i, n-i-1));
return max_val;
}
/* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ int cutRod(int price[], int n) { if (n <= 0) return 0; int max_val = INT_MIN; // Recursively cut the rod in different pieces and compare different // configurations for (int i = 0; i<n; i++) max_val = max(max_val, price[i] + cutRod(price+i, n-i-1)); return max_val; }THe recursive function should work on the new array (price + i) which is a part of the smaller one is it! Correct me if I'm wrong
This is solution I have written:
/* Paste your code here (You may delete these lines if not writing code) */ public class RodDivision { public static int divideRod(int[] values, int[] answers, int n){ if(n==0) return 0; if(answers[n]!=-1) return answers[n]; int max=-1, ans; for(int i=1; i<=n; i++){ ans=values[i]+divideRod(values, answers, n-i); if(ans>max) max=ans; } answers[n]=max; return max; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] values={0,1,5,8,9,10,17,17,20}; int n=values.length-1; int[] answers=new int[values.length]; for(int i=0;i<answers.length; i++) answers[i]=-1; System.out.println(divideRod(values, answers, n)); } }#include<stdio.h> int cutRod(int price[],int n) { int max_val= max((n+1)*price[0],price[n]); int i,max_sofar=0; for(i=0;i<n;i++) { max_sofar = price[i]+price[n-i-1]; if(max_sofar >max_val) max_val = max_sofar ; } return max_val; } int max(int a, int b) { return (a > b)? a : b;} int main() { int arr[] = {2, 5, 8, 9, 10, 17, 17, 20}; int size = sizeof(arr)/sizeof(arr[0]); printf("Maximum Obtainable Value is %d\n", cutRod(arr, size-1)); getchar(); return 0; }I think can be improved little bit.. below is the code of changed for loop...
for (i = 1; i<=n; i++) { //int max_val = price[i]; val[i] = price[i-1]; for (j = 0; j < i/2; j++) val[i]= max(val[i], val[j] + val[i-j]); //val[i] = max_val; }isn't it is similar to the 0-1 knapsack problem where ...
here size of knapsack is length of the rod and number of object available is 1 to length of the rod with corresponding prices of each size wt.
Directly maps to knapsack.. here weight is length of Rod... and objects are smaller pieces where each piece length is weight of each obj and each piece price is each obj value.
Hi Kapil, I think in my solution either we are taking it full or we are not taking it so i thin kit should work with 0-1 knapsack problem. Pleas correct me if I am wrong .. thanks for your comment.
this will not work,here you are applying greedy approach, it will not work here. you study why greedy approach fails for 0-1 knapsack .
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 1 5 8 9 10 17 17 20
DO it like this
1/1 = 1, 5/2 = 2.5, 8/3 = 2.66, 9/4 = 2.25, 10/5 = 2, 17/6 = 2.83, 17/7 = 2.42, 20/8 = 2.5
Now highest is 2.83 we will take 2.83 which is piece 6 we left with 2 more pieces we can either take piece 1 or 2 but piece 2 is now more. so we will 5 which is piece 2.
I think I am right.. Thanks
That will not work always. The reason is same as why greedy algo doesn't work for 0-1 knapsack problem.
great! a good example for beginners to understand DP.