問題描述
解決思路
採用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
花了好長時間才解決的,具體原因不明確
以下爲解決方案:
運行結果
總結
可以結合王曉東 《算法設計與分析》 中的回溯法一章進行研究。