On the knapsack problem, Baidu Library has Tri Tian wing great God's "backpack Nine", unclear please visit. Here are just a few of the most basic 01 knapsack problem implementations.
1 Public classknapsack {2 Private Final intMIN =Integer.min_value;3 4 @org. Junit.test5 Public voidTest () {6 int[] W = {3, 2, 2};7 int[] v = {5, 10, 20};8Knapsackoptimal (5, W, v);9 }Ten One /** A * 01 Backpack-Capacity Compression - * - * @paramC Package Capacity the * @paramweight Quality of each item - * @paramvalue of each item - */ - Public voidKnapsackoptimal (intCint[] weight,int[] value) { + intn = weight.length;//Number of items - int[] W =New int[n + 1]; + int[] v =New int[n + 1]; A int[] G =New int[n + 1] [C + 1]; at for(inti = 1; I < n + 1; i++) { -W[i] = weight[i-1]; -V[i] = value[i-1]; - } - - //Initialize the values[0...c]=0 ———— how much value can be gained without exceeding the backpack capacity in //reason: If the backpack does not have to be filled, then any capacity of the backpack has a legitimate solution "nothing", the value of this solution is 0, so the initial state value is all 0. - int[] values =New int[C + 1]; to //Initialize values[0]=0, others are all negative infinity ———— solve the problem of how much value can be gained in the case of just filling up the backpack + //reason: Only the capacity of 0 of the backpack can be filled with nothing, the value is 0, the other capacity backpack are no legal solution, belong to the undefined state, should be assigned to negative infinity - /*for (int i = 1; i < values.length; i++) { the values[i] = MIN; * }*/ $ Panax Notoginseng for(inti = 1; I < n + 1; i++) { - for(intt = C; T >= W[i]; t--) { the if(Values[t] < Values[t-w[i]] +V[i]) { +VALUES[T] = Values[t-w[i]] +V[i]; AG[i][t] = 1; the } + } - } $SYSTEM.OUT.PRINTLN ("Maximum value is:" +values[c]); $System.out.print ("The item number for the backpack is:"); - /* - output order: Reverse output Item number the Note: Here another open array g[i][v], marking the position of the previous state - G[i][v] = 1: Indicates the item I put in the backpack, the previous state is g[i-1][v-w[i]]Wuyi G[i][v] = 0: Indicates that the item I did not put in the backpack, the previous state is g[i-1][v] the */ - inti =N; Wu intj =C; - while(I > 0) { About if(G[i][j] = = 1) { $System.out.print (i + "")); -J-=W[i]; - } -i--; A } + } the}
The END.
01 knapsack problem (Java implementation)