题意:现在有4种面值的货币,给出每种货币的数量,求是否能用这4种货币组成总额为P.若存在,则输出该方案.
分析:多重背包,数组标记,记录路径.
code:
type rec=record
fa,tot:longint;
end;
var a:array[1..4] of longint=(1,5,10,25);
c,ans:array[1..4] of longint;
f:array[0..10001] of boolean;
count:array[0..10001] of longint;
path:array[0..10001] of rec;
i,j,m,cur:longint;
function sum:longint;
begin
sum:=m+c[1]+c[2]+c[3]+c[4];
end;
procedure init;
begin
read(m);
for i:=1 to 4 do read(c[i]);
if sum=0 then halt;
readln;
end;
procedure work;
begin
fillchar(f,sizeof(f),0);
fillchar(path,sizeof(path),0);
f[0]:=true;
for i:=1 to 4 do
begin
fillchar(count,sizeof(count),0);
for j:=a[i] to m do
if (not f[j] or (path[j-a[i]].tot+1>path[j].tot))
and(f[j-a[i]])and(count[j-a[i]]<c[i]) then
begin
f[j]:=true;
path[j].tot:=path[j-a[i]].tot+1;
path[j].fa:=j-a[i];
count[j]:=count[j-a[i]]+1;
end;
end;
end;
procedure print;
begin
if f[m]=false then
writeln('Charlie cannot buy coffee.')
else
begin
fillchar(ans,sizeof(ans),0);
cur:=m;
while cur<>0 do
begin
case cur-path[cur].fa of
1:inc(ans[1]);
5:inc(ans[2]);
10:inc(ans[3]);
25:inc(ans[4]);
end;
cur:=path[cur].fa;
end;
writeln('Throw in ',
ans[1],' cents, ',
ans[2],' nickels, ',
ans[3],' dimes, and ',
ans[4],' quarters.');
end;
end;
begin
while not eof do
begin
init;
work;
print;
end;
end.
浙公网安备 33010602011771号