#include <iostream.h>
int max(int v1,int v2,int v3)//至少有一个参数为1,故只需三个参数
{
int max=0;
int flag=0;
for (max=2;1;max++)
{
flag=0;
for (int t1=0;t1<4;t1++)
{
for (int t2=0;t2<4-t1;t2++)
{
for (int t3=0;t3<4-t1-t2;t3++)
{
for (int t4=0;t4<4-t1-t2-t3;t4++)
{
if (t1*v1+t2*v2+t3*v3+t4==max)
{
flag=1;
goto CON;
}
}
}
}
}
CON:if (flag) continue;
return max-1;
}
}
int main()
{
int k1,k2,k3;//高1<k1<k2<k3,则km<2(k(m-1)+1)
int rtn=0,maxval=0;
int r1,r2,r3;
for (k1=2;k1<5;k1++)
{
for (k2=k1+1;k2<2*(k1+1);k2++)
{
for (k3=k2+1;k3<2*(k2+1);k3++)
{
rtn=max(k1,k2,k3);
if (maxval<rtn)
{
maxval=rtn;
r1=k1;r2=k2;r3=k3;
}
}
}
}
cout<<'\n'<<"The Result is:"<<r1<<'\t'<<r2<<'\t'<<r3;
cout<<'\n'<<"The Max Value is:"<<maxval<<'\n';
return 0;
}
{$A+,B-,D-,E+,F-,G-,I-,L-,N-,O-,P-,Q-,R-,S-,T-,V-,X+,Y-} {$M 16384,0,655360}
program stamps;
var f,fout:text; n,m,i,j,k:integer;
c:array [1..255] of integer; {面额}
a:array [1..31000] of integer; {递推数组}
bl:boolean;
procedure readfile; {读文件}
begin
assign(f,'STAMP.DAT');
reset(f); assign(fout,'STAMP.OUT');
rewrite(fout);
readln(f,n);
readln(f,m);
bl:=true;
for i:=1 to m do
begin
readln(f,c[i]);
if c[i]=1 then bl:=false;
end;
close(f);
end;
procedure work;
begin
if bl=true then write(fout,'MAX=0') {不存在面额1时输出无解}
else begin
i:=1; a[i]:=1;
repeat
i:=i+1;
for j:=1 to m do
if ((i mod c[j]=0) and ((i div c[j])<a[i]))
or (a[i]=0) {判断它能否被题目给定面额整除} then
a[i]:=i div c[j];
for j:=1 to trunc(i/2) do
if (a[j]+a[i-j]<a[i]) then a[i]:=a[j]+a[i-j]; {寻找(1<=j<=i),使A[j]+A[i-j]值最小}
until (a[i]>n) or (a[i]=0);
write(fout,'MAX=',i-1); {输出}
end;
close(fout);
end;
begin
readfile;
work;
end.
{$A+,B-,D+,E+,F-,G-,I+,L+,N-,O-,P-,Q-,R-,S-,T-,V-,X+}
{$M 16384,0,655360}
program stamps_pro;
uses crt;
var
x:array [1..255] of byte;
pieces:array [0..30000] of byte;
max,m,n,i,j:integer;
filename:string;
f:text;
begin
{读文件}
assign(f,'STAMP.DAT'); reset(f);
readln(f,n); readln(f,m);
for i:=1 to m do readln(f,x[i]);
close(f);
fillchar(pieces,sizeof(pieces),0); max:=0;
{递推循环}
repeat
max:=max+1;
{循环,建立递推关系式PIECES[i]=MAX(PIECES[I-X[j]]+1)}
for i:=1 to m do if max-x[i]>=0 then
begin
if pieces[max]=0 then pieces[max]:=pieces[max-x[i]]+1;
if pieces[max]>pieces[max-x[i]]+1
then pieces[max]:=pieces[max-x[i]]+1;
end;
{输出无解}
if (pieces[max]=0) or (pieces[max]>n) then
begin
writeln('MAX=',max-1); exit;
end;
until false;
end.
程序优化后,运行四组测试数据时间如下: (测试机型:Pentium MMX 233)
测试数据 m N 未优化程序运行时间(秒) 优化程序运行时间(秒)
1 5 10 0.05 0.11
2 3 5 0.06 0.11
3 10 20 0.61 0.17
4 70 65 6.75 0.33
5 100 100 20.20 1.20