量牛奶

给你n个桶子以及它们的容积,用最少且字典序最小的桶子量出Q升牛奶。

答案保证不超过3,于是乱搞,,,,,,考试的时候写的,写的很丑。

program Neayo;
const
        inf='milk.in';
        ouf='milk.out';
var
        i,ans,j,k,q,n,top,closed,step:longint;
        a:array[0..101]of longint;
        b:array[0..3]of longint;
        use:array[0..101]of  boolean;
        h:array[0..20000]of longint;
        c:array[0..20000]of boolean;
procedure init;
var x,y:longint;
begin
     assign(input,inf);assign(output,ouf);
     reset(input);rewrite(output);
     readln(q);
     readln(n);
     x:=0;y:=0;
     for i:=1 to n do
     begin
          read(x);
          if h[x]>0 then continue;
          h[x]:=1;
          inc(y); a[y]:=x;
          if q mod a[y]=0 then
          begin
               if a[y]<ans then ans:=a[y];
          end;
     end;
     fillchar(h,sizeof(h),0);
     close(input);
end;
procedure qsort(l,r:longint);
var i,j,tmp,x:longint;
begin
     i:=l;j:=r;
     x:=a[l+random(r-l+1)];
     repeat
           while a[i]<x do inc(i);
           while a[j]>x do dec(j);
           if i<=j then
           begin
                tmp:=a[i];a[i]:=a[j];a[j]:=tmp;
                inc(i);
                dec(j);
           end;
     until(i>j);
     if i<r then qsort(i,r);
     if l<j then qsort(l,j);
end;
procedure bfs(x:longint);
begin
     top:=0;closed:=x;
     fillchar(c,sizeof(c),false);
     fillchar(h,sizeof(h),0);
     for i:=1 to x do h[i]:=b[i];
     repeat
           inc(top);
           for i:=1 to x do
           if (h[top]+b[i]<=q)and(not c[h[top]+b[i]]) then
           begin
                inc(closed);
                h[closed]:=h[top]+b[i];
                c[h[closed]]:=true;
                if c[q] then
                begin
                     write(x,' ');
                     for x:=1 to x do
                     write(b[x],' ');
                     exit;
                end;
           end;
     until(top>closed);
end;
procedure dfs(time,pre:longint);
var i:longint;
begin
     if time=step then
     begin
           bfs(time-1);
           if c[q] then exit;
           fillchar(c,sizeof(c),false);
           exit;
     end;
     for i:=pre to n do
     begin
          b[time]:=a[i];
          dfs(time+1,i+1);
          if c[q] then exit;
     end;
end;
procedure go;
begin
     qsort(1,n);
     step:=3;
     dfs(1,1);
     if not c[q] then
     begin
          step:=4;
          dfs(1,1);
     end;
end;
begin
     ans:=maxlongint;
     init;
     if ans<maxlongint then writeln(1,' ',ans)
     else go;
     close(output);
end.    
posted @ 2012-10-14 20:47  neayo  阅读(183)  评论(0编辑  收藏  举报