第15章动态规划------算法导论

15.1钢条切割

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<ctime> 
#include<string>
using namespace std;
int p[1000]{ 0,1,5,8,9,10,17,17,20,24,30 };//钢条价格。长度i的价格为p[i]
int ordinary(int *p, int n)//递归法
{
	if (n == 0)
		return 0;
	else
	{
		int q = -1;
		for (int i = 1; i <= n; ++i)
		{
			q = max(p[i] + ordinary(p, n - i), q);
		}
		return q;
	}
}
int top_down_memory(int *p, int n)//动态规划 带备忘的自顶向下法  与递归法类似,只是结果存储起来了
{
	static int b[1000];
	if (n == 0)
		return 0;
	if (b[n] != 0)
	{
		return b[n];
	}
	else
	{
		int q = -1;
		for (int i = 1; i <= n; ++i)
		{
			q = max(p[i] + top_down_memory(p, n - i), q);
		}
		b[n] = q;
		return q;
	}
}
int bottom_up_method(int *p, int n)//动态规划 自底向上 把子结果都先求出来,再求总结果
{
	static int b[1000];
	for (int i = 1; i <= n; ++i)
	{
		int q=-1;
		for (int j = 1; j <= i; ++j)
		{
			q = max(q, p[j] + b[i - j]);
		}
		b[i] = q;
	}
	return b[n];
}
int bottom_up_method_result(int *p, int n)//动态规划 自底向上 把子结果都先求出来,再求总结果 同时把如何切割求出来
{
	static int b[1000];
	static int s[1000];//切割方案
	for (int i = 1; i <= n; ++i)
	{
		int q = -1;
		int ss = -1;
		for (int j = 1; j <= i; ++j)
		{
			if (q < p[j] + b[i - j])
			{
				q = p[j] + b[i - j];
				ss = j;
			}
		}
		s[i] = ss;
		b[i] = q;
	}
	return b[n];
}
int main()
{
	int n;
	clock_t start;
	
	while (cin>>n)
	{
		start = clock();
		cout << ordinary(p, n);
		cout << "ordinary:" << double(clock() - start) << " ";
		start = clock();
		cout << bottom_up_method_result(p, n);
		cout<< "bottom_up_method_result:" << double(clock()-start) << " ";
		start = clock();
		cout << top_down_memory(p, n);
		cout << "top_down_memory:"<< double(clock() - start)  << endl;
	}
}

  

猜你喜欢

转载自www.cnblogs.com/l2017/p/10284323.html
今日推荐