Problem: Given a rope with length n, how to cut the rope into m parts with length n[0], n[1], ...,n[m-1], in order to get the maximal product of n[0]*n[1]*
... *n[m-1]? We have to cut once at least. Additionally, the length of the whole length of the rope, as well as the length of each part, are in integer value.
For example, if the length of the rope is 8, the maximal product of the part lengths is 18. In order to get the maximal product, the rope is cut into three parts with lengths 2, 3, and 3 respectively.
参考:http://codercareer.blogspot.com/2013/12/no-52-maximal-product-when-cutting-rope.html
/* Copyleft: Ming Lin <minggr@gmail.com> */
#include <stdio.h>
#include <stdlib.h>
int *max;
void init_max(int n)
{
int i;
max = (int*)malloc((n+1)*sizeof(int));
for (i = 0; i <= n; i++)
max[i] = -1;
}
int cut_dp(int n)
{
int m = 0;
int i;
if (max[n] != -1)
return max[n];
if (n < 2) {
max[n] = 1;
goto exit;
}
if (n == 2) {
max[n] = 2;
goto exit;
}
if (n == 3) {
max[n] = 3;
goto exit;
}
for (i = 1; i <= n/2; i++) {
m = cut_dp(i) * cut_dp(n-i);
if (m > max[n])
max[n] = m;
}
exit:
return max[n];
}
int cut_dp2(int n)
{
int m;
int i, j;
max[1] = 1;
max[2] = 2;
max[3] = 3;
for (i = 4; i <= n; i++) {
m = 0;
for (j = 1; j <= i/2; j++) {
max[i] = max[j] * max[i-j];
if (max[i] > m)
m = max[i];
}
max[i] = m;
}
return m;
}
int cut(int n)
{
if (n == 1)
return 0;
if (n == 2)
return 1;
if (n == 3)
return 2;
return cut_dp2(n);
}
int main()
{
int n = 8;
init_max(n);
printf("%d\n", cut(n));
return 0;
}
本文探讨如何通过最优切割绳子,使切割后的部分长度乘积达到最大。通过动态规划算法解决绳子切割问题,给出求解过程及具体实例。
569

被折叠的 条评论
为什么被折叠?



