Maximal Product when Cutting Rope

本文探讨如何通过最优切割绳子,使切割后的部分长度乘积达到最大。通过动态规划算法解决绳子切割问题,给出求解过程及具体实例。
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;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值