您的位置:首页 > 其它

背包问题

2015-09-09 16:36 302 查看
背包问题需要用到动态规划的思想

const int GOODS_NUM = 5;
int g_goodsValue[GOODS_NUM] = {6, 3, 6, 2, 5};
int g_goodsWeight[GOODS_NUM] = {2, 4, 7, 5, 3};
int g_maxValue[10][5];	//剩余空间为i时,装j件物品能获得最大的价值

int GetMaxValue(int space, int num)
{
	int res;
	if(g_maxValue[space][num] != -1)
	{
		res = g_maxValue[space][num];
	}
	else if(num == 0)	//如果仅有1件物品
	{
		if(space > g_goodsWeight[num])
		{
			res = g_goodsValue[num];
		}
		else
		{
			res = 0;
		}
	}
	else if((num != 0) && space > g_goodsWeight[num])	//如果剩余的空间够装下这件物品
	{
		res = max(g_goodsValue[num] + GetMaxValue(space - g_goodsWeight[num], num - 1),
				  GetMaxValue(space, num - 1));
	}
	else
	{
		res = GetMaxValue(space, num - 1);
	}

	g_maxValue[space][num] = res;	//做备忘录,这里不太理解
	return res;
}

int main()
{
	//初始化
	for(int i = 0; i <= 10; i++)
		for(int j = 0; j < 5; j++)
			g_maxValue[i][j] = -1;
	//剩余空间为10,5件物品(物品编号0-4),所能取得的最大价值
	std::cout << GetMaxValue(10, 4) << std::endl;
	getchar();
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: