TheAlgorithms-C-Plus-Plus/dynamic_programming/Cut Rod.cpp

29 lines
712 B
C++
Raw Normal View History

2016-12-01 22:14:32 +08:00
/*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.*/
2020-04-18 10:43:43 +08:00
#include <iostream>
2016-12-01 22:14:32 +08:00
using namespace std;
2019-08-21 10:10:08 +08:00
int cutrod(int p[], int n)
2016-12-01 22:14:32 +08:00
{
2019-08-21 10:10:08 +08:00
int r[n + 1];
r[0] = 0;
for (int j = 0; j < n; j++)
2016-12-01 22:14:32 +08:00
{
2019-08-21 10:10:08 +08:00
int q = INT_MIN;
for (int i = 0; i <= j; i++)
2016-12-01 22:14:32 +08:00
{
2019-08-21 10:10:08 +08:00
q = max(q, p[i] + r[j - i]);
2016-12-01 22:14:32 +08:00
}
2019-08-21 10:10:08 +08:00
r[j + 1] = q;
2016-12-01 22:14:32 +08:00
}
return r[n];
}
int main()
{
2019-08-21 10:10:08 +08:00
int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50};
cout << cutrod(price, 30);
2016-12-01 22:14:32 +08:00
return 0;
}