Cod sursa(job #145793)

Utilizator Pepelea_FlaviuFlaviu Pepelea Pepelea_Flaviu Data 29 februarie 2008 15:09:24
Problema Evaluarea unei expresii Scor 20
Compilator fpc Status done
Runda Arhiva educationala Marime 2.61 kb
var fi,fo:text;
    s:ansistring;
    semn,c:array[0..100000]of char;
    rez:array[1..100000]of longint;
    op:array[0..100000]of string[11];
    vf,ct:longint;
procedure push(vl:char);
begin
  c[vf]:=vl;
  inc(vf);
end;
procedure pop(var vl:char);
begin
  dec(vf);
  vl:=c[vf];
end;
procedure solve;
var i,n:longint;
begin
  n:=0;
  for i:=1 to ct do
    if op[i][1] in ['0'..'9'] then
      begin
        inc(n); val(op[i],rez[n]);
        if semn[i]='-' then rez[n]:=-rez[n];
      end
    else
      begin
        if op[i]='+' then rez[n-1]:=rez[n-1]+rez[n]
         else
          if op[i]='-' then rez[n-1]:=rez[n-1]-rez[n]
           else
            if op[i]='*' then rez[n-1]:=rez[n-1]*rez[n]
             else
              if op[i]='/' then rez[n-1]:=rez[n-1] div rez[n];
         dec(n);
       end;
  writeln(fo,rez[1]);
end;
procedure eval;
var lung,i:longint;
    aux:char;
    nr:string[11];
begin
  lung:=length(s);
  nr:=''; ct:=0;
  for i:=1 to lung do
    begin
      if s[i] in ['0'..'9'] then nr:=nr+s[i]
       else
        if s[i]='(' then push(s[i])
         else
          if s[i]=')' then
            begin
              inc(ct); op[ct]:=nr; nr:='';
              while (c[vf-1]<>'(')and(vf<>1) do
                begin
                  pop(aux); inc(ct); op[ct]:=aux;
                end;
              pop(aux);
            end
          else
           if s[i] in ['+','-'] then
             if (s[i]='-')and(s[i-1]='(') then semn[ct+1]:='-'
              else
               begin
                 if nr<>'' then
                   begin
                     inc(ct); op[ct]:=nr; nr:='';
                   end;
                 while (vf<>1)and(c[vf-1]<>'(') do
                   begin
                     pop(aux); inc(ct); op[ct]:=aux;
                   end;
                 push(s[i]);
               end
           else
            if s[i] in ['*','/'] then
              begin
                if nr<>'' then
                  begin
                    inc(ct); op[ct]:=nr; nr:='';
                  end;
                while (vf<>1)and(c[vf-1] in ['*','/']) do
                  begin
                    pop(aux); inc(ct); op[ct]:=aux;
                  end;
                push(s[i]);
              end;
    end;
  if nr<>'' then
    begin
      inc(ct); op[ct]:=nr;
    end;
  while vf<>1 do
    begin
      pop(aux); inc(ct); op[ct]:=aux;
    end;
  solve;
end;
begin
  assign(fi,'evaluare.in'); reset(fi);
  assign(fo,'evaluare.out'); rewrite(fo);
  readln(fi,s);
  vf:=1;
  eval;
  close(fi);
  close(fo);
end.