算法导论15.1-3

今天每周报告表现不好,比较郁闷。便看看算法导论调节心情,第一次看英文原版的动态规划,感觉还比较爽,写写后面的习题。

基本思路,切的次数cutNumber(n) = cutNumber(n-i)+1 (应当小于允许的最长分段);收入:maxValue(n)=maxValue(n-i)+baseValue(i)-COST;其中baseValue是已知条件。不过要注意的是n==i时候没有分段,那么不应该减去COST

#include<iostream>
using namespace std;
void findSolution(int lenth,int firstCut[]);	//reverse topological sort to find the solution
#define COST 4
int main()
{
	int kind, lenth;
	int valueBased[100] = {0};
	int tempValue[1000];		 //record the value of section
	int lenthSection[100];		 //record the lenth of section 
	cout<<"input kinds of sections and value of each section"<<endl;
	cin>>kind;

	for(int i=1; i<=kind; i++)
		cin>>lenthSection[i]>>valueBased[i];
	cout<<"input the lenth of the rob to be dealt with"<<endl;
	cin>>lenth;

	for(int i=1;i<=lenth;i++)
		tempValue[i] = -1;
	tempValue[0] = 0;
	
	/*following: the down-to-up-cut-rod*/
	int firstCut[1000] = {0};	//record the firstCut of the rod,so we can reverse sort to find the solution to get the most value
	int cutNumber[1000] = {0};  //record the number of cutting to calculate the most value
	
	for(int i=1;i<=lenth;i++)
		{
			int max = -1;
			int temp = 0;		//judge whether to reduce the cost
			for(int j=1;j<=kind;j++)
			{
				if(i==lenthSection[j])
					temp = 0;
				else
					temp = 1;
				if((valueBased[j] + tempValue[ i- lenthSection[j] ]-COST*temp)>max)
					{
						max = valueBased[j] + tempValue[i- lenthSection[j]] - COST*temp;
						firstCut[i] = lenthSection[j];
						cutNumber[i] = cutNumber[i-lenthSection[j]] + temp;
					}
			}
			tempValue[i] = max;
		}
	/*to put information of each lenth's*/ 
	/*
	for(int i=1;i<lenth;i++)
		{
			printf("lenth:%d, value:%d, firstCut:%d cutNumber:%d \n",i,tempValue[i],firstCut[i], cutNumber[i]);
		}
	*/
	printf("\nlenth:%d value:%d firstCut:%d cutNumber:%d \n",lenth,tempValue[lenth],firstCut[lenth], cutNumber[lenth]);
	/*example: to get the current number inputted of the most value*/
	findSolution(lenth,firstCut);
	system("pause");
	return 1;
}


/*reverse topological sort to find the solution*/
void findSolution(int temp,int firstCut[1000])
{
	cout<<endl<<"the best segmention method:"<<endl;
	while(temp>0)
	{
		cout<<firstCut[temp]<<"  ";
		temp = temp - firstCut[temp];
	}
	cout<<endl;
}




你可能感兴趣的:(算法,System,each)