DFS求解0-1背包

 

var
    w,p:array[1..10000] of longint;
    x,bestx:array[1..10000] of 0..1;
    c,bestp,n,i:longint;

procedure DFS(i,cp,cw:longint);
var j:longint;
begin
    if i>n then
    begin
        if cp>bestp then
        begin
            bestp:=cp;
            for j:=1 to i do bestx[j]:=x[j];
        end;
        exit;
    end;
    x[i]:=0;  DFS(i+1,cp,cw);
    if(cw+w[i]<=c)then
    begin
        x[i]:=1;  DFS(i+1,cp+p[i],cw+w[i]);
    end;
end;

begin
    readln(c,n);
    for i:=1 to n do read(w[i]);
    for i:=1 to n do read(p[i]);
    DFS(1,0,0);
    writeln(bestp);
    for i:=1 to n-1 do write(bestx[i],' ');
    writeln(bestx[n]);
end.

 

posted @ 2014-10-31 15:07  qilinart  阅读(207)  评论(0)    收藏  举报