算法導論 動態規劃之鋼條切割

#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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章