1 ProgramPackage ;2 Const 3maxm= $; maxn= -;4 var 5 M,n,j,i:integer;6C,w:Array[1.. MAXN] ofinteger;7F:Array[0.. MAXN,0.. MAXM] ofinteger;8 functionMax (X,y:integer): integer; //to find the maximum value of x and Y9 beginTen ifX>y ThenMax:=xElsemax:=y; One End; A
- BEGIN -Assign (input,'package.in'); theAssign (output,'Package.out'); - reset (input); - rewrite (output); -READLN (M,n); //backpack capacity m and number of items n + fori:=1 toN Do -READLN (W[i],c[i]); //weight and value of each item + fori:=1 toN Do A forj:=1 toM Do at begin//f (i,x) denotes the top I item, the total weight does not exceed the optimal value of x - ifJ>=w[i] ThenF[i,j]:=max (f[i-1, j-w[i]]+c[i],f[i-1, J]) - Elsef[i,j]:=f[i-1, j]; - End; -Writeln (F[n,m]); //F (n,m) is the optimal solution - close (input); in close (output); -END.
It is convenient to use a two-dimensional array to store each sub-problem, but when the MAXM is large, you cannot define a two-dimensional array F, but you can actually use a one-dimensional array.
1 ProgramStar_package;2 var3 I,j,k,n,m:longint;4F:Array[0..100000] ofLongint;5W,c:Array[0.. -] ofLongint;6 begin7Assign (input,'package.in');8Assign (output,'Package.out'); 9 reset (input);Ten rewrite (output); OneFillchar (F,sizeof (f),0); AREADLN (M,n); //backpack capacity m and number of items n - fori:=1 toN Do -READLN (W[i],c[i]); //weight and value of each item the fori:=1 toN Do - forJ:=mDowntoW[i] DoThis cannot be written for J:=w[i] tom - ifF[J-W[I]]+C[I]>F[J] ThenF[j]:=f[j-w[i]]+c[i]; //F (j) means the maximum value of the weight not exceeding J kg - Writeln (f[m]); + close (input); - Close (ouptut); + End.
0/1 Backpack