01 Backpack (recursively resolve)

01 backpack, set a backpack, he had a maxweight, now you have n items, each item has its weight and its value, now you seek the greatest value achieved.

Using the idea of ​​recursion, if now is a beginning from the last election, if the weight of this thing is greater than the weight of the backpack, it is not possible to start from the selected objects of n-1.

If the weight is less than the weight of the backpack thing, so now you will face two options, one is not selected, then you skip this article, can be selected from n-1 starts. Second, the election, if you choose, then the weight of the backpack is reduced, and increase the value of the backpack, it can be given a number to store the value and continue from the beginning of the next election. Finally Comparison n, n-1 ,. . . . The size of the value to zero. For a given function can be a comparison of the maximum output value.

code show as below:

#include <iostream>
#include<iomanip>
using namespace std;
struct A //建立结构体储存重量与价值
{
	int weight;
	int value;
}bag[100];
int find(int weight,int n)//递归函数,返回最大值
{	
	if (weight == 0 || n == 0) return 0;//如果背包容量==0或者物体个数==0 那么返回0.
	else 
		if (bag[n-1].weight > weight)  return find(weight, n-1); //如果最后一个物体的重量大于背包容量,那么寻找下一个物体。
			else
			{
				int temp1 = find(weight, n-1);		//假如容量大于物体的质量 那么面临选择,  若不选则跳过,进行下一个物体的选择
				int temp2 = bag[n-1].value+find(weight - bag[n-1].weight, n-1); //若进行选择 则记录价值大小,并减去物体的质量,再进行下一个物体的选择。
				return temp2 > temp1 ? temp2 : temp1;//返回价值最大的值。
			}
}
int main()
{	
	int bagweight, num;
	cin >> bagweight;
	cin >> num;
	for (int i = 0; i < num; i++)
	{
		cin >> bag[i].weight >> bag[i].value;
	}
	cout << find(bagweight, num);
}
Published 17 original articles · won praise 1 · views 3436

Guess you like

Origin blog.csdn.net/weixin_43983570/article/details/90381025