算法导论 动态规划之钢条切割

#include<iostream>
#include<algorithm>
using namespace std;
int UpToBottom(int *p,int n)//普通的自顶向下实现
{
	if (n == 0)
		return 0; 
	int q = -1;
	for (int i = 1; i <= n; i++)
	{
		q = max(q, p[i]+UpToBottom(p, n - i));
	}
	return q;
}





int UpToBottom_memory(int *p, int n, int *r)//带备忘录版本的 自顶向下实现
{
	if (r[n] >= 0)
		return r[n];//在备忘录中查询存在,直接返回
	if (n == 0)
		return 0;
	int q = -1;
	for (int i = 1; i <= n; i++)
	{
		q = max(q, p[i] + UpToBottom_memory(p, n - i, r));
	}
	r[n] = q;
	return q;
}
int Init_Memory(int *p,int n) //初始化数组
{
	int r[1000];
	for (int i = 0; i != n; i++)
		r[i] = -1;
	return UpToBottom_memory(p, n, r);
}






int BottomToUp(int *p,int n)//自底向上版本
{
	int r[1000];
	r[0] = 0;
	int q;
	for (int j = 1; j <= n; j++)
	{
		q = -1;
		for (int i = 1; i <=j; i++)
		{
			q = max(q,r[j-i]+p[i]);//不采用递归,直接调用r[j-i]获取规模为j-i的子问题的解.
		}
		r[j] = q;
	}
	return r[n];
}

 

int main()
{
	int arr[1000] = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
	cout << "钢条长度20,自顶向下结果:" << UpToBottom(arr, 20) << endl;
	cout << "钢条长度25,带备忘录的自顶向下结果:" << Init_Memory(arr, 25) << endl;;
	cout << "钢条长度30,自底向上结果:" << BottomToUp(arr, 30) << endl;
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值