TREEPATH - Đường đi trên cây

Tác giả: flashmt

Ngôn ngữ: Pascal

const fi='';
      fo='';
      base=100000000;
      digit=8;
type bignum=array[0..251] of longint;
var num,re,cur,pre,t:bignum; st:ansistring; l,i:longint;

procedure put(var x:bignum;y:longint);
var i:longint;
begin
     for i:=1 to x[0] do x[i]:=0;
     x[0]:=1; x[1]:=y;
end;

procedure plus(var c:bignum;a,b:bignum);
var i,mem,max:longint;
begin
     mem:=0;
     if a[0]>b[0] then max:=a[0] else max:=b[0];
     for i:=1 to max do
     begin
          c[i]:=a[i]+b[i]+mem;
          if c[i]<base then mem:=0
          else begin
                     mem:=1; c[i]:=c[i] mod base;
          end;
     end;
     if mem>0 then
     begin
          max:=max+1;
          c[max]:=mem;
     end;
     c[0]:=max;
end;

procedure multi(var c:bignum;a:bignum;b:longint);
var i,mem,max:longint;
begin
     mem:=0; max:=a[0];
     for i:=1 to max do
     begin
          c[i]:=a[i]*b+mem;
          if c[i]<base then mem:=0
          else begin
                     mem:=c[i] div base; c[i]:=c[i] mod base;
          end;                    
     end;
     if mem>0 then
     begin
          max:=max+1;
          c[max]:=mem;
     end;
     c[0]:=max;
end;

procedure mul(var c:bignum;a:bignum;b:longint);
var i,mem,max:longint;
begin
     mem:=0; max:=a[0];
     for i:=1 to max do
     begin
          c[i]:=a[i] shl b+mem;
          if c[i]<base then mem:=0
          else begin
                     mem:=c[i] div base; c[i]:=c[i] mod base;
          end;                    
     end;
     if mem>0 then
     begin
          max:=max+1;
          c[max]:=mem;
     end;
     c[0]:=max;
end;

procedure pr(c:char);
begin
     multi(pre,pre,3);
     if c<>'L' then
     begin
          plus(pre,pre,num);
          if c='R' then plus(pre,pre,num);
     end;
     plus(re,re,pre);
end;

procedure star;
begin 
     mul(re,re,2);
     multi(cur,pre,9);
     multi(t,num,3);
     plus(cur,cur,t);
     plus(num,num,t); 
     plus(re,re,cur);
     plus(pre,pre,cur);  
end;

procedure rf;
var c:char;
begin
     assign(input,fi);
     reset(input); read(st); l:=length(st);
     re[0]:=1; num[0]:=1; pre[0]:=1; 
     put(re,1); put(num,1); put(pre,1); 
     for i:=1 to l do
     begin
          if st[i]='S' then continue;
          if st[i]='*' then star
          else pr(st[i]);
     end;
     close(input);
end;

procedure wf;
var i,j,t:longint; s:string;
begin
     assign(output,fo);
     rewrite(output);
     for i:=re[0] downto 1 do
     begin
          if i<re[0] then
          begin
               str(re[i],s);
               t:=length(s);
               for j:=t+1 to digit do write(0);
          end;
          write(re[i]);
     end;
     close(output);
end;

begin
     rf;
     wf;
end.




























Download