zoukankan      html  css  js  c++  java
  • 背包问题——dfs

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

     


     

     

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

    以下为解决方案:

     


     

     

    运行结果

     

    测试用例
    测试用例

     

     

    运行结果
    运行结果

     

    总结

    可以结合王晓东  《算法设计与分析》 中的回溯法一章进行研究。
  • 相关阅读:
    Python reportlab table 设置cellstyle枚举,设置单元格padding
    代理工具 v2ra*的使用
    python 开发环境需要安装
    postgres 新增或者更新语句
    python psycopg2 查询结果返回字典类型
    postgres 多个字段匹配查询
    django 执行原生sql形参传递,字段参数传递
    亚马逊接口调用
    python x 开头的字符转码为中文
    postgres 定义变量
  • 原文地址:https://www.cnblogs.com/Howbin/p/10585693.html
Copyright © 2011-2022 走看看