[NOJ1004] [algorithm experiment 2] [backtracking algorithm] 0-1 knapsack problem

Posted by mrkite on Sun, 22 Dec 2019 22:31:03 +0100

1004.0-1 knapsack problem

Time limit: 1000ms memory limit: 10000K total time limit: 3000ms

describe

The backpack with capacity of c shall be loaded. Select the items i n the backpack from the n items. The weight of each item I is wi and the value is pi. For feasible knapsack loading, the total weight of the items in the knapsack cannot exceed the capacity of the knapsack, and the best loading refers to the highest value of the items.

 

input

There are several cases, each of which has three lines of input.

The first line has two integers: n (n < = 10) and c,

In the second line, n integers are w1 to wn,

The third n integers are p1 to pn.

n and c are equal to zero mark the end of input.

 

output

The output of each test case takes up one line and outputs an integer, that is, the total value of the best load.

#include <iostream>

using namespace std;

int n,c;    //n is the number, c is the capacity
int w[11];  //weight
int v[11];  //value
int wn,vn;  //Current weight and current value
int vmax;   //Maximum value

void dfs(int m);        //Backtracking and deep search
bool overweight(int m); //Judge whether it is overweight at present
bool cut(int m);        //prune

int main()
{
    int i;
    cin>>n>>c;
    while(!(n==0&&c==0)){  //End when both n and c are 0
        //input data
        for(i=0;i<n;i++)
            cin>>w[i];
        for(i=0;i<n;i++)
            cin>>v[i];

        //Initialization
        wn=vn=vmax=0;


        //Process and output data
        dfs(0);
        cout<<vmax<<endl;

        //Next input data
        cin>>n>>c;
    }
    return 0;
}

void dfs(int m)
{
    if(m==n){
        if(vn>vmax){
            vmax=vn;
        }
    }
    else{
        if(!cut(m)){
            if(!overweight(m)){
                wn+=w[m];
                vn+=v[m];
                dfs(m+1);
                vn-=v[m];
                wn-=w[m];
            }
            dfs(m+1);
        }
    }
}
bool overweight(int m)   //Judge whether it is overweight
{
    if(wn+w[m]>c)       //If the load m is overweight
        return true;
    else
        return false;
}
bool cut(int m)         //prune
{
    int v_remain=0;
    for(int i=m;i<n;i++){
        v_remain+=v[i];     //Calculate item m and the value of all remaining items
    }
    if(vn+v_remain<vmax)    //If the current value and the value of all the remaining items add up
        return true;        //It's not as big as the current vmax, so there's no need to search again
    else
        return false;
}