编辑代码

#include<iostream>
#include<math.h>
using namespace std;
int inOut[5];
int value;
int bagVolume = 9;
bool bagConstraint(int m, int weight[]) {
	int allweight = 0;
	for (int i = 0; i <= m; ++i)
	{
		allweight += inOut[i] * weight[i];
	}
	return allweight <= bagVolume;
}
void bagProblem(int m, int weight[], int valueAll[]) {
	if (m == 5)
	{
		int sum = 0;
		for (int i = 0; i < m; ++i)
		{
			sum += valueAll[i] * inOut[i];
		}
		if (sum > value)
		{
			value = sum;
		}
	}
	else {
		for (int i = 0; i < 2; ++i)
		{
			inOut[m] = i;
			if (bagConstraint(m, weight))
			{
				bagProblem(m + 1, weight, valueAll);
			}
		}

	}

}

int main(int argc, char const* argv[])
{
	cout << "物品数量:5" << endl;
	cout << "背包容量:10" << endl;
	cout << "重量分别是:6,5,4,2,1" << endl;
	cout << "价值分别是:5,3,5,3,2 " << endl;
	int num = 5;
	int weight[5] = { 6,5,4,2,1 };
	int valueAll[5] = {5,3,5,3,2 };
	bagProblem(0, weight, valueAll);
	cout << "最大的价值是:" << value << endl;
	cout << endl;
	return 0;

}