Public classMain {/** * * @paramValue *@paramweight *@paramC Backpack Capacity *@paramm M (i,j) backpack capacity is J, can choose the best value of the backpack when the item is i,i+1,..., n*/ Public Static voidKnapsack (int[] Value,int[] weight,intCint[] m) { intn = value.length-1; //initialization: The optimal value of the selected item for each value of the backpack capacity range when only the nth item is selected intJmax =math.min (Weight[n], c); for(intj = 0; J <= Jmax; J + +) {M[n][j]= 0; } for(intj = Weight[n]; J < C; J + +) {M[n][j]=Value[n]; } //Optional items are i,i+1,..., n-1, the optimal value of the selected items for each value of the backpack capacity range for(inti = n-1; i > 0; i--) {Jmax=math.min (Weight[i], c); for(intj = 0; J < Jmax; J + +) {M[i][j]= M[i + 1][j]; } for(intj = Weight[i]; J < C; J + +) {M[i][j]= Math.max (M[i + 1][j], M[i + 1][j-weight[i]] +Value[i]); } } //Optional items are,..., n, the optimal value of the selected item with a backpack capacity of CM[0][C] = m[1][c]; if(C > weight[0]) {m[0][C] = Math.max (M[0][c], m[1][c-weight[0]] + value[0]); } } /*** Get the best solution *@paramm *@paramweight *@paramc *@paramx*/ Public Static voidTracebackint[] m,int[] weight,intCint[] x) { intn = weight.length-1; for(inti = 0; I < n; i++) { if(M[i][c] < M[i + 1][c]) {X[i]= 0; }Else{X[i]= 1; C-=Weight[i]; }} X[n]= M[n][c] > 0? 1:0; } /** * @paramargs*/ Public Static voidMain (string[] args) {intc = 10; int[] weight = {5, 5, 5}; int[] value = {10,5,11}; int[] m =New int[Weight.length] [C + 1]; Knapsack (value, weight, C, M); int[] x={0,0,0}; Traceback (m, weight, C, x); System.out.println ("Best Value:" + m[0][c]); System.out.print ("The best solution is:"); for(inti = 0; i < x.length; i++) {System.out.print (X[i]+ ((i! = x.length-1)? ",":"")); } System.out.println ("\ n"); System.out.println ("The matrix of the best values is:"); for(inti = 0; i < weight.length; i++) { for(intj = 0; J < C + 1; J + +) {System.out.print (M[i][j]+ ((J! = c)? "," :"")); } System.out.print ("\ n"); } }}
The result is:
The optimal value is: 21
The best solution is: 1,1,0
The matrix of the optimal values is:
0,0,0,0,0,0,0,0,0,0,21
0,0,0,0,0,11,11,11,11,11,0
0,0,0,0,0,11,11,11,11,11,0
01 knapsack problem