DFS例题1

#include<cstdio>

/*
	n件物品,每件物品重量为w[i],价值为c[i]。
	选出若干件物品放入容量为V的背包中, 
	在选入背包的物品重量和不超过容量V的前提下,让背包中物品的价值之和最大 
*/



const int maxn = 30;
int n, V, maxValue = 0;	//物品件数n,背包容量V,最大价值maxValue 
int w[maxn], c[maxn];	//w[i]为每件物品的重量,c[i]为每件物品的价值 

//index为当前处理的物品编号
//sumW为当前总重量,sumC为当前总价值 
void DFS(int index, int sumW, int sumC){	 
	if(index == n){
		if(sumW <= V && sumC > maxValue){
			maxValue = sumC;
		}
		return;
	}
	//DFS岔道口 
	DFS(index + 1, sumW, sumC);	//不选第index件物品 
	DFS(index + 1, sumW + w[index], sumC + c[index]);	//选第index件物品 
}


//优化,剪枝
int ans = 0;
void DFS2(int index, int sumW, int sumC){
	if(index == n) return;
	DFS(index + 1, sumW, sumC);
	if(sumW + w[index] <= V){
		if(sumC + c[index] > ans) ans = sumC + c[index];
		DFS(index + 1, sumW + w[index], sumC + c[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);
	DFS2(0, 0, 0);
	printf("%d\n", maxValue);
	printf("%d\n", ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值