问题:给你一根长度为n的绳子,请把绳子剪成m段(m,n都是整数,n>1,m>1),每段绳子的长度记为k[0],k[1],...,k[m]。请问k[0]*k[1]*...k[m]可能的最大乘积是多少?
#include<iostream>
#include<math.h>
using namespace std;
int maxProductAfterCutting_solution(int length);
int maxProductAfterCutting_solution2(int length);
int main()
{
cout <<"0: "<< maxProductAfterCutting_solution(0) <<endl;
cout <<"1: "<< maxProductAfterCutting_solution(1) << endl;
cout <<"2: "<< maxProductAfterCutting_solution(2) << endl;
cout <<"3: "<< maxProductAfterCutting_solution(3) << endl;
cout <<"4: "<< maxProductAfterCutting_solution(4) << endl;
cout <<"5: "<< maxProductAfterCutting_solution(5) << endl;
cout <<"6: "<< maxProductAfterCutting_solution(6) << endl;
cout <<"7: "<< maxProductAfterCutting_solution(7) << endl;
cout << "8: " << maxProductAfterCutting_solution(8) << endl;
cout << "9: " << maxProductAfterCutting_solution(9) << endl;
cout << "10: " << maxProductAfterCutting_solution(10) << endl;
cout << "11: " << maxProductAfterCutting_solution(11) << endl;
system("pause");
return 0;
}
int maxProductAfterCutting_solution(int length) {
if (length < 2) {
return 0;
}
if (length==2)
{
return 2;
}
if (length ==3)
{
return 3;
}
int *products = new int[length +1];
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max = 0;
for (size_t i = 4; i <=length; i++)
{
int mid = i / 2;
max = 0;
for (size_t j = 1; j <= mid; j++)
{
int tmp = products[j] * products[i - j];
if (max< tmp)
{
max = tmp;
}
products[i] = max;
}
}
max = products[length];
delete[] products;
return max;
}
int maxProductAfterCutting_solution2(int length) {
if (length<2)
{
return 0;
}
if (length ==2)
{
return 2;
}
if (length == 3)
{
return 3;
}
int time3 = length / 3;
int time4 = 0;
if (length%3 ==1)
{
time3 = time3 - 1;
time4 = 1;
}
int time2 = (length - 3 * time3)/2;
return (pow(3, time3) * pow(2, time2));
}