#include<iostream>
#include<algorithm>
using namespace std;
//动态规划
int maxProductAfterCutting_soution(int length)
{
if (length < 2)
return 0;
if (length == 2)
return 1;
if (length == 3)
return 2;
int* products = new int[length + 1];
//注意这里对于products的初始几个数,当长度大于等于4时,f(5) = f(3)*f(2) = 2*3 ;
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max = 0;
for (int i = 4; i <= length; ++i)
{
max = 0;
for (int j = 0; j <= i / 2; ++j)
{
int product = products[j] * products[i - j];
if (max < product)
max = product;
products[i] = max;
}
}
max = products[length];
delete[] products;
return max;
}
//贪婪算法
int maxProductAfterCutting_soution2(int length)
{
if (length < 2)
return 0;
if (length == 2)
return 1;
if (length == 3)
return 2;
int timesOfthree = length / 3;
if (length - timesOfthree * 3 == 1)
timesOfthree -= 1;
int timesOftwo = (length - timesOfthree * 3) / 2;
return (int)(pow(3, timesOfthree))*(int)(pow(2, timesOftwo));
}
int main()
{
int max1 = 0;
int max2 = 0;
max1 = maxProductAfterCutting_soution(50);
max2 = maxProductAfterCutting_soution2(50);
cout << max1 << " " << max2;
cin.get();
return 0;
}
代码中应注意对数组products的初始的赋值。