第八章 搜索专题(深度搜索)——背包问题

#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=30;
int n,V,maxvalue=0; //物品件数n,背包容量V
int w[maxn],c[maxn]; //w[i]为每件物品的重量,c[i]为每件物品的价值

/*void DFS(int index,int sumw,int sumc)//index为当前处理物品的编号,sumw,sumc分别为当前总重量和总价值
{
	if(index==n)
	{
		if(sumw<=V&&sumc>maxvalue)
			maxvalue=sumc;
		return ;
	}
	//岔道口
	DFS(index+1,sumw,sumc);//不拿第index+ 1件物品
	DFS(index+1,sumw+w[index],sumc+c[index]); //拿第index件物品 
}*/
//剪枝后的DFS 
void DFS(int index,int sumw,int sumc)
{
	if(index==n)
		return ;//已完成对n件物品的选择 
	DFS(index+1,sumw,sumc);//不选第index件物品 
	if(sumw+w[index]<=V) 
	{
		if(sumc+c[index]>maxvalue)	
			maxvalue=sumc+c[index];//更新最大值 
		
		DFS(index+1,sumw+w[index],sumc+c[index]); //选第index件物品 
	}
}


int main()
{
	scanf("%d%d",&n,&V);
	for(int i=0;i<n;++i)
		scanf("%d",&w[i]);
	for(int i=0;i<n;++i)
		scanf("%d",&c[i]);
	DFS(0,0,0);//初始对第0件物品、当前总重量,当前总价值均为0
	printf("%d\n",maxvalue);
	return 0; 
 } 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值