//Author: FF-W
//Date: 9, Oct, 2018
//Purpose: 0-1背包问题(回溯法)
#include <iostream>
using namespace std;
int vBest=0;
bool check(int t,int vCurrent,int V[],int nItem)
{
int vSum=0;
for(int i=t;i<nItem;i++)
{
vSum+=V[i];
}
if(vSum+vCurrent>vBest)
return true;
return false;
}
void getitemBest(int item[],int itemBest[],int nItem)
{
for (int i=0;i<nItem;i++)
{
itemBest[i]=item[i];
}
}
void backtraceing(int t,int item[],int V[],int W[],int nItem,int wAll,int itemBest[],int wCurrent,int vCurrent)
{
if(t>=nItem)
{
vBest=vCurrent;
getitemBest(item,itemBest,nItem);
return;
}
if(wCurrent+W[t]<=wAll&&check(t,vCurrent,V,nItem))
{
item[t]=1;
wCurrent+=W[t];
vCurrent+=V[t];
backtraceing(t+1,item,V,W,nItem,wAll,itemBest,wCurrent,vCurrent);
wCurrent-=W[t];
vCurrent-=V[t];
}
if(check(t+1,vCurrent,V,nItem))
{
item[t]=0;
backtraceing(t+1,item,V,W,nItem,wAll,itemBest,wCurrent,vCurrent);
}
}
void output(int item[],int nItem)
{
for(int i=0;i<nItem;i++)
{
if(item[i])
{
cout<<"第"<<i+1<<"个 ";
}
}
cout<<endl;
}
int main()
{
cout<<"背包问题"<<endl;
cout<<"请输入背包总容量:"<<endl;
int wAll;
cin>>wAll;
cout<<"请输入物品个数:"<<endl;
int nItem;
cin>>nItem;
int W[nItem];
int V[nItem];
cout<<"请输入物品价值和质量:"<<endl;
int item[nItem]={0};
int itemBest[nItem]={0};
for(int i=0;i<nItem;i++)
{
cin>>V[i]>>W[i];
}
backtraceing(0,item,V,W,nItem,wAll,itemBest,0,0);
cout<<"为使得背包中物品价值最大,选择如下序列:"<<endl;
output(itemBest,nItem);
cout<<"总价值为"<<vBest;
return 0;
}
0-1背包问题(回溯法)
最新推荐文章于 2022-05-07 12:14:29 发布