#include
#include
#include
int cutRod(int* p, int n);
int memoryCutRod(int* p, int n);
int memoryCutRodAux(int* p, int n, std::vector& r);
int bottomUpCutRod(int*p, int n);
int main()
{
int p[10] = {1,5,8,9,10,17,17,20,24,30};
int n = 4;
//first method
int r = cutRod(p, 4);
std::cout << "max r:" << r << std::endl;
//second method
r = memoryCutRod(p,4);
std::cout << "max r:" << r << std::endl;
//third mehod
r = bottomUpCutRod(p, 4);
std::cout << "max r:" << r << std::endl;
return 0;
}
int cutRod(int* p, int n)
{
if (n == 0)
return 0;
int q = INT_FAST32_MIN;
for (int i = 1; i <= n; i++)
{
q = std::max(q, p[i-1] + cutRod(p, n-i));
}
return q;
}
int memoryCutRod(int* p, int n)
{
std::vector r(n + 1, INT_FAST32_MIN);
return memoryCutRodAux(p, n, r);
}
int memoryCutRodAux(int* p, int n, std::vector& r)
{
if (r[n] >= 0)
return r[n];
int q = INT_FAST32_MIN;
if (n == 0)
q = 0;
else
{
for (int i = 1; i <= n; i++)
q = std::max(q, p[i-1] + memoryCutRodAux(p, n-i, r));
}
r[n] = q;
return q;
}
int bottomUpCutRod(int*p, int n)
{
std::vector r(n + 1, INT_FAST32_MIN);
r[0] = 0;
for (int j = 1; j <= n; j++)
{
int q = INT_FAST32_MIN;
for (int i = 1; i <= j; i++)
{
q = std::max(q, p[i-1] + r[j-i]);
}
r[j] = q;
}
return r[n];
}
5 输出
max r:10
max r:10
max r:10
6 参考
算法导论