Backtracking and 0-1 knapsack problem

Given items in n and a backpack with a capacity of c, the weight of item i is Wi, and its value is Vi, 0-1 The backpack problem is how to choose the items to be loaded into the backpack (items are indivisible) so that the items are loaded into the backpack The value is the greatest.

 

 

1. Subject analysis:

Considering that there are only 2 options for each item, namely loading a backpack or not loading it, and the number of items and the capacity of the backpack have been given, to calculate the maximum value of the items loaded into the backpack and the optimal loading plan, the backtracking method can be used to search The algorithm of the subset tree is solved.

2. Algorithm design:
a. There are n kinds of items, the backpack capacity is C, p[i] and w[i] are used to store the value and weight of the i-th item, and
x[i] is used to mark whether the i-th item is loaded Enter the backpack, 0 means not to take this item, 1 means to take this item, use bestx[i] to store the optimal loading plan of the i-th item;
b. Use the recursive function Backtrack (i,cp,cw) to achieve backtracking Method search subset tree (formal parameter i represents the depth
of recursion , n is used to control the depth of recursion, formal parameters cp and cw represent the current total value and total weight, bestp represents the current
optimal total value):
① If i> n, then The algorithm searches for a leaf node and judges whether the current total value is optimal:
1> If cp>bestp, update the current optimal total value to the current total value (ie bestp=cp), and update the
loading plan (ie bestx[i]= x[i]( 1≤i≤n));
② Use the for loop to discuss the two cases of item i with and without loading (0≤j≤1):
1> x[i]=j;
2> If the total If the weight is not greater than the backpack capacity (ie cw+x[i]*w[i]<=c), update the current total price and total weight (ie cw+=w[i]*x[i] ,cp+=p[i]*x[i]), call the recursive function
Backtrack(i+1,cp,cw) to item i+1 to continue loading;
3> function Backtrack(i+1,cp,cw) After the call, it returns the current total value and total weight
(Ie cw-=w[i]*x[i],cp-=p[i]*x[i]);
4> When j>1, the for loop ends;
③ When i=1, if it has After testing all loading schemes, the outer layer calls are all over;
c. The main function calls backtrack(1,0,0) once to complete the entire backtracking search process, and the final bestp and bestx[i] are the maximum total required Value and optimal loading plan.

 

Java implementation:

public class KnapsackProblem {
    static int n, c, bestp;//The number of items, the capacity of the backpack, the maximum value
    static int[] p = new int[10000], w = new int[10000], x = new int[10000], bestx = new int[10000];//Item value, item weight, x[i] The selection of temporary storage items, the selection of items

    public static void main(String[] args) {
        bestp = 0;
        KnapsackProblem kp = new KnapsackProblem();
        // Example 1
        c = 10;
        n = 10;
        w = new int[]{2, 2, 6, 5, 4, 4, 3, 4, 6, 3};
        p = new int[]{6, 3, 5, 4, 6, 2, 8, 3, 1, 7};
        kp.dfsByBackTraching(0, 0, 0);
        System.out.println(bestp);
        for (int s = 0; s < 10; s++) {
            System.out.print(bestx[s] + "  ");
        }
        System.out.println();
        // Example 2
        c = 5;
        n = 4;
        w = new int[]{1, 2, 3, 4};
        p = new int[]{2, 4, 4, 5};
        bestp = 0;
        Arrays.fill(x, 0);
        Arrays.fill(bestx, 0);
        KnapsackProblem kp1 = new KnapsackProblem();
        kp1.dfsByBackTraching(0, 0, 0);
        System.out.println(bestp);
        for (int s = 0; s < 4; s++) {
            System.out.print(bestx[s] + "  ");
        }
    }


    void dfsByBackTraching(int i, int cp, int cw) {//cw current item weight in the package, cp current item value in the package
        int j;
        if (i >= n) {//The end of the traceback
            if (cp> bestp) {//whether the maximum value is exceeded
                bestp = cp; //Update the maximum value
                for (i = 0; i < n; i++) {
                    bestx[i] = x[i]; //Get the selected item, the following table corresponding to the element whose bestx[i] value is 1 is the selected item number
                }
            }
        } else {
            for (j = 0; j <= 1; j++) {
                x[i] = j;
                if (cw + x[i] * w[i] <= c) {//Satisfy the constraints, continue to explore the child nodes
                    cw += w[i] * x[i];
                    cp + = p [i] * x [i];
                    dfsByBackTraching(i + 1, cp, cw);
                    //Go back to the selection of the previous layer
                    cw -= w[i] * x[i];
                    cp - = p [i] * x [i];
                }
            }
        }

    }
}

 

Reference: https://blog.csdn.net/u011889952/article/details/44303699

Guess you like

Origin blog.csdn.net/daobuxinzi/article/details/109508892