码迷,mamicode.com
首页 > 其他好文 > 详细

背包问题——dfs

时间:2019-03-23 22:19:36      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:back   cti   microsoft   oid   play   ges   span   content   graph   

背包问题——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

 

技术图片
 

 

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

以下为解决方案:

 

技术图片
 

 

运行结果

 

技术图片
测试用例

 

 

技术图片
运行结果

 

总结

可以结合王晓东  《算法设计与分析》 中的回溯法一章进行研究。

背包问题——dfs

标签:back   cti   microsoft   oid   play   ges   span   content   graph   

原文地址:https://www.cnblogs.com/Howbin/p/10585693.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!