背包问题——dfs


问题描述

在这里插入图片描述

解决思路

采用DFS搜索  其实也是回溯法

代码实现

#include<iostream>
#include<vector>
using namespace std;
struct goods
{
	int w;
	int v;
	int flag;
};
vector<goods> g;
vector<goods> result;
int n;       	//货物数
int space;   	//空间
int nowspa;  	//剩余空间 
int nowval;   //当前价值
int maxval=0;    //最大价值 
void bfs(int i, int nowspa, int nowval);
int main()
{
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
	cin>>n;
	cin>>space;
	for(int i=0; i<n; i++)
	{
		goods temp;
		temp.flag=1;
		cin>>temp.w;
		g.push_back(temp);	
	} 
	
	for(int i=0; i<n; i++ )
	{
		cin>>g[i].v;
	}
    vector<goods>::iterator it=g.begin();
    for(;it!=g.end(); it++)
    {
    	goods temp=*it;
    	cout<<temp.v<<endl;
    	cout<<temp.w<<endl;
    	cout<<temp.flag<<endl;
	}
	bfs(0, space, 0);
	cout<<"maxval="<<maxval<<endl;
	cout<<"装载方案"<<endl;
    it=result.begin();
    for(;it!=result.end(); it++)
    {
    	goods temp=*it;
    	cout<<temp.flag<<endl;
	}
	return 0;
}
void bfs(int i, int nowspa, int nowval)
{
	if(i==n)
	{
		if(maxval<nowval)
		{
			maxval=nowval;
			result=g;
		}
		return ;
	}
	//装
	if(nowspa>=g[i].w)
	{
		 g[i].flag=0;
		 bfs(i+1,nowspa-g[i].w, nowval+g[i].v);
	}
	g[i].flag=1;
	bfs(i+1,nowspa, nowval);
}

编写中的bug

bug1

在这里插入图片描述

花了好长时间才解决的,具体原因不明确

以下为解决方案:

在这里插入图片描述

运行结果

在这里插入图片描述

在这里插入图片描述

总结

可以结合王晓东  《算法设计与分析》 中的回溯法一章进行研究。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值