补充,上次链家笔试的0-1背包问题

本文介绍了一种解决0-1背包问题的具体实现方法,并通过一个逃亡情境的例子进行说明。代码使用C++编写,详细展示了如何计算在给定背包容量限制下能够容纳的最大价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上次同学链家笔试,有一道0-1背包的问题不会做,当时百度了一下,没看太懂,今天来补充一下自己做的代码:

问题:明明和乔乔一起逃亡,要求输入第一行,第一个数表示输入几行数据,第二个数表示背包的容量,接下来的几行第一个数表示该物品的个数,第二个数表示物品的重量,第三个数表示物品的价值。求,在背包容量的限度内,能装多少价值的物品?

例: 2   10

                 3    4    3

                 2    2    5

        输出:  13

int Dp(vector<int> &weight,vector<int> &value,int num,int maxweight)
{
	vector<vector<int> > end(num+1);
	for(int i = 0; i <= num; ++i)
		end[i].resize(maxweight+1);
	cout<<num<<"    "<<maxweight<<endl;
	for(int i = 1; i <= num; ++i)
	{
		end[i][0] = 0;
		for(int j = 1; j <= maxweight; ++j)
		{       //如果表示重量的下标比该物品的重量下,则和之前的数据相同
			if(j < weight[i-1])
				end[i][j] = end[i-1][j];
			else
			{       //否则将计算,之前重量的背包所能容量的价值和不装该物品的价值的最大值
				int tmp = end[i-1][j - weight[i-1]] + value[i-1];
				if(tmp < end[i-1][j])
					end[i][j] = end[i-1][j];
				else
					end[i][j] = tmp;
			}
		}
	}
//一下代码为寻找路径,和0-1背包的实质计算没有关系。
	//vector<int> path(num+1);
	//for(int i = num,j = maxweight; i > 0; --i)
	//{
	//	if(end[i][j] == end[i-1][j])
	//		path[i] = 0;
	//	else
	//	{
	//		path[i] = 1;
	//		j -= weight[i-1];
	//	}
	//}
	//copy(path.begin(),path.end(),ostream_iterator<int>(cout," "));
	return end[num][maxweight];
}
void main()
{
	int num,maxweight;
	cin>>num>>maxweight;
	int tmp = 0;
	vector<int> weight;
	vector<int> value;
	for(int i = 0; i < num; ++i)
	{
		int tmp_tmp;
		cin>>tmp_tmp;
		tmp += tmp_tmp;
		int tmp_tmp_tmp;
		cin>>tmp_tmp_tmp;
		for(int j = 0; j < tmp_tmp; ++j)
		{
			weight.push_back(tmp_tmp_tmp);
		}
		cin>>tmp_tmp_tmp;
		for(int j = 0; j < tmp_tmp; ++j)
			value.push_back(tmp_tmp_tmp);
	}
	cout<<Dp(weight,value,tmp,maxweight)<<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值