#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;
}
算法导论 动态规划之钢条切割
最新推荐文章于 2021-03-03 21:08:26 发布