Cod sursa(job #145940)

Utilizator Pepelea_FlaviuFlaviu Pepelea Pepelea_Flaviu Data 29 februarie 2008 19:14:20
Problema Evaluarea unei expresii Scor 100
Compilator fpc Status done
Runda Arhiva educationala Marime 2.4 kb
const nmax=100001;
var fi,fo:text;
    rez:array[0..nmax]of longint;
    cc:array[0..nmax]of char;
    vf,ct:longint;
    s:ansistring;
procedure push(vl:char);
begin
  inc(vf);
  cc[vf]:=vl;
end;
procedure solve(poz:longint);
begin
  if cc[poz]='+' then rez[ct-1]:=rez[ct-1]+rez[ct];
  if cc[poz]='-' then rez[ct-1]:=rez[ct-1]-rez[ct];
  if cc[poz]='*' then rez[ct-1]:=rez[ct-1]*rez[ct];
  if cc[poz]='/' then rez[ct-1]:=rez[ct-1] div rez[ct];
  dec(ct);
end;
procedure eval;
var i,put,last,numb,j:longint;
begin
  ct:=0; numb:=0;
  for i:=1 to length(s) do
    begin
      if s[i]='(' then push('(')
       else
        if s[i] in ['0'..'9'] then
          begin
            numb:=numb*10+ord(s[i])-48;
            put:=1;
          end
        else
         if s[i]=')' then
           begin
             if put=1 then
               begin
                 inc(ct); rez[ct]:=numb;
                 numb:=0; put:=0; end;
             for j:=vf downto 1 do
               if cc[j]<>'(' then solve(j)
                else
                  begin vf:=j-1; break; end;
           end
         else
          if s[i] in ['+','-'] then
            begin
              if put=1 then
                begin
                  inc(ct); rez[ct]:=numb;
                  numb:=0; put:=0; end;
              for j:=vf downto 0 do
                if cc[j] in ['*','/','-','+'] then solve(j)
                  else
                     begin vf:=j; break; end;
              push(s[i]);
            end
          else
           if s[i] in ['*','/'] then
             begin
               if put=1 then
                 begin
                   inc(ct); rez[ct]:=numb;
                   numb:=0; put:=0; end;
               for j:=vf downto 0 do
                 if cc[j] in ['/','*'] then
                   begin
                     if cc[j]='/' then rez[ct-1]:=rez[ct-1] div rez[ct]
                      else rez[ct-1]:=rez[ct-1]*rez[ct];
                     ct:=ct-1;
                   end
                 else begin vf:=j; break; end;
               push(s[i]);
             end;
    end;
  if s[length(s)]<>')' then
    begin
      ct:=ct+1; rez[ct]:=numb; end;
  for j:=vf downto 1 do
    solve(j);
  writeln(fo,rez[1]);
end;
begin
  assign(fi,'evaluare.in'); reset(fi);
  assign(fo,'evaluare.out'); rewrite(fo);
  readln(fi,s);
  eval;
  close(fi);
  close(fo);
end.