物品装箱问题(文件名:box.c/cpp/pas)
设有n 种物品,记作 A1、A2、…、An,对应于每个Ai(1<=i<=n)都有一个重量Awi和价值 Avi (重量和价值都为正整数)。另外,对应于每个 Ai,都有一件可代替它的“代用品”Bi,Bi的重量和价值分别为Bwi 和Bvi。
本题的任务是:选择这 n 件物品或其代用品的一个子集装进背包,使总重量不超过给定重量 TOT,同时使总价值VAL 最高。装填的第I步,要么装入Ai,要么装入 Bi,要么 Ai
和 Bi 都不装。
输入数据:
第一行:n TOT ,n<=100, TOT<=10000
第二行:AW1 A v1 B W1 Bv1
第三行:AW2 A v2 B W2 Bv2
……
第 n+1行:AWn A vn B Wn Bvn
输入数据:
只有一个数为最大的价值
样例
输入文件:box.in
4 20
8 20 12 31
2 3 9 20
13 31 11 12
8 9 13 36
输出文件:box.out
40
=========================
完全背包,就地滚动....
=========================
type
re=record
w,v:longint;
end;
var
n,tot:longint;
a,b:array[1..100]of re;
f:array[0..10000]of longint;
procedure init;
begin
assign(input,'box.in');
assign(output,'box.out');
reset(input); rewrite(output);
end;
procedure terminate;
begin
close(input); close(output);
halt;
end;
function max(a,b:longint):longint;
begin
if a>b then exit(a);
exit(b);
end;
procedure main;
var
i,j:longint;
begin
readln(n,tot);
for i:=1 to n do
begin
readln(a[i].w,a[i].v,b[i].w,b[i].v);
end;
fillchar(f,sizeof(f),0);
for i:=1 to n do
for j:=tot downto 0 do
begin
if j>=a[i].w then
f[j]:=max(f[j-a[i].w]+a[i].v,f[j]);
if j>=b[i].w then
f[j]:=max(f[j-b[i].w]+b[i].v,f[j]);
end;
writeln(f[tot]);
end;
begin
init;
main;
terminate;
end.