This is a C++ Program that Solves Rod Cutting Problem using Dynamic Programming technique.
Given a rod of size n and values of various sizes of rod. The problem is to cut the rod in such a way that the sum of values of the pieces is maximum.
The problem can be solved by calculating the maximum attainable value of rod by cutting in various pieces in a bottom up fashion by first calculating for smaller value of n and then using these values to calculate higher values of n.
The time complexity of this solution is O(n^2).
n=5 value= 2 3 7 8 10 for sizes 1,2,3,4,5 respectively Expected result=11 by cutting the rod in pieces of sizes 1,1 and 3
n=7 value= 2 7 8 25 17 28 30 Expected result=34 by cutting the rod in pieces of sizes 1,2 and 4
Here is source code of the C++ Program to Solve Rod Cutting Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
using namespace std;
int rodCutting(int n, int value)
//we will calculate the maximum attainable value of rod in a bottom up fashion by first calculating for smaller value of n and then using these values to calculate higher values of n
//create an array to store the results
//result[i]=maximum attainable value of rod of size i
//in every iteration, find the result for rod of size i
//try to cut the rod of length i into various values of j and select the one which gives the maximum value
cout<<"Enter the length of the rod"<<endl;
//value[i]=value of rod of size i+1
//value=value of rod of size 1
//value=value of rod of size 2
cout<<"Enter the values of pieces of rod of all size"<<endl;
cout<<"Maximum obtainable value by cutting up the rod in many pieces are"<<endl;
In the main function, we ask the user to input the length of rod and values of pieces of rod of all size. We pass these values to the function rodCutting as parameters. This function will calculate the expected result and return it. The returned value will be displayed.
Case-1: $ g++ rod_cutting.cpp $ ./a.out Enter the length of the rod Enter the length of the rod 7 Enter the values of pieces of rod of all size 2 7 8 25 17 28 30 Maximum obtainable value by cutting up the rod 34
Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.