01背包(回溯法)

#include
using namespace std;
int n;
int m;
int w[101];
int v[101];
int best=0;
int cw=0;//记录背包中当前的物品重量
int cv=0;//记录背包中当前的物品价值
int s=0;//记录不拿这个商品剩余的总价值
int  flag(int t)
{
    for(int i=t;i<n;i++)
        s+=v[i];
    return s+cv;
}
void dfs(int t)
{
    if(t>=n)//探索到了叶子结点
    {
        if(cv>best)
        best=cv;
        return;
    }
    if(cw+w[t]<=m)//探索左子树,即将这个物品放入背包
    {
        cw+=w[t];
        cv+=v[t];
        dfs(t+1);//回溯
        cw-=w[t];
        cv-=v[t];
    }
    if(flag(t+1)>best)//探索右子树
    {
        dfs(t+1);
    }
}
int main()
{
    cin>>n>>m;
    for(int i=0;i<n;i++)
    {
        cin>>w[i]>>v[i];
    }
    dfs(0);
    cout<<best;
}



你可能感兴趣的:(01背包(回溯法))