题目:给你一根长度为n绳子,请把绳子剪成m段(m、n都是整数,n>1并且m≥1)。每段的绳子的长度记为k[0]、k[1]、……、k[m]。k[0]*k[1]*…*k[m]可能的最大乘积是多少?例如当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到最大的乘积18。
分别用动态规划和贪婪算法
#include<iostream>
using namespace std;
//动态规划
int maxProductAfterCutting_solution(int length)
{
//判断边界
int max;
if (length < 2)
return 0;
if (length == 2)
return 1;
if (length == 3)
return 2;
//最优解存储在products中
int*products = new int[length + 1];
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
//i递增,从下到上保存最优解
for (int i = 4;i <= length;++i)
{
max = 0;
//分别求出i的最优解
for (int j = 1;j <= i / 2;++j)
{
int product = products[j] * products[i - j];
if (product > max)
max = product;
}
products[i] = max;
}
max = products[length];
//最后还要释放内存
delete[] products;
return max;
}
//贪婪算法
int maxProductAfterCutting(int length)
{
//特殊情况处理
if (length < 2)
return 0;
if (length == 2)
return 1;
if (length == 3)
return 2;
//求出×3的次数
int timesof3 = length / 3;
//当长度为4时,不能再剪,更好的是2*2>3*1
if (length - timesof3 * 3 == 1)
timesof3 -= 1;
//求出×2的次数
int timesof2 = (length - timesof3 * 3) / 2;
return (int)(pow(3, timesof3))*(int)(pow(2, timesof2));
}
//测试输入
void Test1()
{
printf("乘积最大值为:%d \n",maxProductAfterCutting_solution(0));
printf("乘积最大值为:%d \n", maxProductAfterCutting(0));
}
void Test2()
{
printf("乘积最大值为:%d \n", maxProductAfterCutting_solution(1));
printf("乘积最大值为:%d \n", maxProductAfterCutting(1));
}
void Test3()
{
printf("乘积最大值为:%d \n", maxProductAfterCutting_solution(2));
printf("乘积最大值为:%d \n", maxProductAfterCutting(2));
}
void Test4()
{
printf("乘积最大值为:%d \n", maxProductAfterCutting_solution(3));
printf("乘积最大值为:%d \n", maxProductAfterCutting(3));
}
void Test5()
{
printf("乘积最大值为:%d \n", maxProductAfterCutting_solution(4));
printf("乘积最大值为:%d \n", maxProductAfterCutting(4));
}
void Test6()
{
printf("乘积最大值为:%d \n", maxProductAfterCutting_solution(5));
printf("乘积最大值为:%d \n", maxProductAfterCutting(5));
}
int main()
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}