1 Program knapsack;
2 Const
3 maxm=200;maxn=30;
4 var
5 i,j,n,m:integer;
6 w,u:array[1..maxn] of integer;
7 f:array[0..maxn,0..maxm] of integer;
8
9 BEGIN
10 assign(input,'knapsack.in');
11 assign(output,'knapsack.out');
12 reset(input); rewrite(output);
13 fillchar(w,sizeof(w),0);
14 fillchar(u,sizeof(u),0);
15 readln(m,n);
16 for i:=1 to n do
17 read(w[i],u[i]);
18 for i:=1 to n do
19 begin
20 for j:=1 to w[i]-1 do
21 f[i,j]:=f[i-1,j];
22 for j:=w[i] to m do
23 if f[i-1,j]>f[i,j-w[i]]+u[i] then f[i,j]:=f[i-1,j]
24 else f[i,j]:=f[i,j-w[i]]+u[i];
25 end;
26 writeln('max=', f[n,m]);
27 close(input); close(output);
28 END.
1 program knapsack04;
2 const maxm=200;maxn=30;
3 type ar=array[0..maxn] of integer;
4 var
5 m,n,j,i,t:integer;
6 u,w:ar;
7 f:array[0..maxm] of integer;
8 BEGIN
9 assign(input,'knapsack.in');
10 assign(output,'knapsack.out');
11 reset(input); rewrite(output);
12 readln(m,n);
13 for i:= 1 to n do
14 readln(w[i],u[i]);
15 f[0]:=0;
16 for i:=1 to n do
17 for j:= w[i] to m do
18 begin
19 if f[j-w[i]]+u[i]>f[j] then f[j]:= f[j-w[i]]+u[i] ;
20 end;
21 writeln(‘max=’,f[m]);
22 close(input);close(output);
23 END.
推荐:通过金矿模型介绍动态规划