01背包问题-动态规划

#include 
#include
using namespace std;

void bag_test_print()
{
	vectorweight = { 1,3,4 };
	vectorvalue = { 15,20,30 };
	int bagweight = 4;
	vector>dp(weight.size(), vector(bagweight + 5, 0));
	for (int j = weight[0]; j <= bagweight; j++)
	{
		dp[0][j] = value[0];
	}
	for (int i = 1; i < weight.size(); i++)
	{
		for (int j = 1; j <= bagweight; j++)
		{
			if (j < weight[i])
			{
				dp[i][j] = dp[i - 1][j];
			}
			else
			{
				dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
			}
		}
	}
	cout << "最大价值为" << dp[weight.size() - 1][bagweight] << endl;
	cout << "dp表为:" << endl;


	for (int i = 0; i < weight.size(); i++)
	{
		for (int j = 0; j <= bagweight; j++)
		{
			cout << dp[i][j] << " ";
		}
		cout << endl;
	}
}

int main()
{
	bag_test_print();
	system("pause");
	return 0;
}

你可能感兴趣的:(算法学习,动态规划,算法)