PackageCom.cjs.zeroonepackage; Public classZeroonepackage {/*** Calculate 0-1 knapsack problem * *@paramW * Incoming backpack weight array *@paramv * Incoming Backpack value array *@paramc * Total capacity of incoming backpack *@returnMaxvalue[n][c] The maximum value of a backpack can be loaded with items*/ Public Static intZeroonepackage (intW[],intV[],intc) {intn = w.length;//Number of items int[] MaxValue =New int[n + 1] [C + 1];//storing an array of the value of items placed in a backpack//Initialize for(inti = 0; I <= N; i++) {maxvalue[i][0] = 0; } for(inti = 0; I <= C; i++) {maxvalue[0][i] = 0; } for(inti = 1; I <= N; i++) { intt = w[i-1] > c? C:W[I-1];//prevents problems with the weight of items that are larger than the total capacity of the backpack for(intj = 1; J < T; J + +) {//backpack remaining capacity than item weight hours, not putMAXVALUE[I][J] = maxvalue[i-1][j]; } for(intj = W[i-1]; J <= C; J + +) {////when the remaining capacity of the backpack is larger than the item weight, putMAXVALUE[I][J] = Math.max (Maxvalue[i-1][j], maxvalue[i-1][j-W[i-1]] + v[i-1]); } } returnMaxvalue[n][c]; }}
C + + implementation
#include <iostream>using namespacestd;intZeroonepackage (intW[],intV[],intCintN) { intmaxvalue[n+1][c+1]; //Initialize for(inti =0; I <= N; i++) {maxvalue[i][0] =0; } for(inti =0; I <= C; i++) {maxvalue[0][i] =0; } for(inti =1; I <= N; i++) { intt = w[i-1] > C? c:w[i-1]; for(intj =1; J < T; J + +) {Maxvalue[i][j]= maxvalue[i-1][j]; } for(intj = w[i-1]; J <= C; J + +) {Maxvalue[i][j]= Max (maxvalue[i-1][J], maxvalue[i-1][j-w[i-1]]+v[i-1]); } } returnmaxvalue[n][c];}intMain () {intN,c; intw[ -],v[ -]; while(cin>>c>>N) { for(inti =0; I < n; i++) {cin>>w[i]>>V[i]; } cout<<"Result:"<<zeroonepackage (w,v,c,n) <<Endl; } return 0;}
0-1 knapsack problem