usaco 2.3 zerosum 2008.6.21

本文介绍了一个USACO竞赛题目ZeroSum的解决方法,使用Pascal语言实现。该程序通过递归生成所有可能的加减组合,并对这些组合进行排序,最终输出所有使表达式结果为零的有效序列。

usaco 2.3 zerosum 2008.6.21

{

ID:

PROG: zerosum

LANG: PASCAL

}

program p_zerosum;

const r:array[1..9]ofchar=('1','2','3','4','5','6','7','8','9');

var

 ans:array[1..9000]of string;

 f1,f2:text;

 x,y:string;

 i,n,p,l:longint;

 

procedure qsort(i1,j1:longint);

var

 l1,r1:longint;x1,y1:string;

   begin

      l1:=i1;r1:=j1;

      x1:=ans[(l1+r1) div 2];

      repeat

      while ans[l1]<x1 do inc(l1);

      while ans[r1]>x1 do dec(r1);

       if l1<=r1 then

                 begin

                       y1:=ans[l1];ans[l1]:=ans[r1];ans[r1]:=y1;inc(l1);dec(r1);

                 end;

      until l1>r1;

      if r1>i1 then qsort(i1,r1);

      if l1<j1 then qsort(l1,j1);

      end;

procedure init;

begin

  assign(f1,'zerosum.in');reset(f1);

  assign(f2,'zerosum.out');rewrite(f2);

  read(f1,n);p:=n-1;l:=0;x:='+- ';

end;

procedure put;

var i:longint;

begin

 inc(l);ans[l]:='';

  fori:=1 to p do

   ans[l]:=ans[l]+y[i]+r[i+1];

    ans[l]:='1'+ans[l];

end;

procedure count;

  vart,j:longint;

 begin

 

   if y[1]<>' ' then begin t:=1;i:=1 end

     else begin

            t:=12;i:=2;

          end;

    repeat inc(i);j:=i-1;

      if (y[j]='+')and(y[i]<>' ') then inc(t,i);

      if (y[j]='+')and(y[i]=' ') then begin t:=t+i*10+i+1;inc(i);end;

      if (y[j]='-')and(y[i]<>' ') then dec(t,i);

      if (y[j]='-')and(y[i]=' ') then begin t:=t-i*10-i-1;inc(i);end;

    until i>=n;

    if t=0 then put;

  end;

procedure deal(k:longint);

var i:longint;

  begin

    if k>p then begin count;exit;end;

    for i:=1 to 3 do

        if (i<>3)or(y[k-1]<>' ') then

         begin y[k]:=x[i];

                  deal(k+1);end;

  end;

{------------------------main---------------------------}

begin

 init;

 deal(1);

 qsort(1,l);

  fori:=1 to l do

    writeln(f2,ans[i]);

  close(f1);close(f2);

end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值