Cod sursa(job #2547957)

Utilizator Arteni_CristiArteni Cristi Arteni_Cristi Data 15 februarie 2020 21:47:40
Problema Evaluarea unei expresii Scor 90
Compilator fpc Status done
Runda Arhiva educationala Marime 1.95 kb
var t,fp:array[0..100005] of int64;
    sgn,st:array[0..50005] of char;
    s:ansistring;
    n,i,a,q,k:longint;

//t[] stiva finala de calcul
//fp[] retinerea numerelor
//sgn[] semnele
// n contorul pentru fp[] si sgn[] impreuna
//st[] stiva de retinere a semnelor in functie de prioritate { '('__0  '*/'__1  '+-'__2)

begin
assign(input,'evaluare.in'); reset(input);
assign(output,'evaluare.out'); rewrite(output);
readln(s);
for i:=1 to length(s) do
 begin
  if (ord(s[i])-48>=0) and (ord(s[i])-48<=9) then
   begin
    q:=1;
    a:=a*10+ord(s[i])-48
   end
  else
   begin
    if q=1 then
     begin
      inc(n);
      fp[n]:=a;
      q:=0; a:=0
     end;
    if pos(s[i],'(+-*/')<>0 then
     begin
      inc(k);
      st[k]:=s[i];
      if (st[k]='+') or (st[k]='-') then
       while pos(st[k-1],'+-*/')<>0 do
        begin
         inc(n);
         sgn[n]:=st[k-1];
         st[k-1]:=st[k];
         dec(k)
        end else
      if (st[k]='*') or (st[k]='/') then
       while (st[k-1]='*') or (st[k-1]='/') do
        begin
         inc(n);
         sgn[n]:=st[k-1];
         st[k-1]:=st[k];
         dec(k)
        end
     end else
    if s[i]=')' then
     begin
      while st[k]<>'(' do
       begin
        inc(n);
        sgn[n]:=st[k];
        dec(k)
       end;
      dec(k)
     end
   end
 end;
//verific daca nu a ramas un numar la final {ex : 3-7}
if q=1 then
 begin
  inc(n);
  fp[n]:=a
 end;
//scot toate semnele care au ramas in stiva de prioritati a semnelor
while k>0 do
 begin
  inc(n);
  sgn[n]:=st[k];
  dec(k)
 end;
k:=0;
for i:=1 to n do
 begin
  if pos(sgn[i],'+-*/')=0 then
   begin
    inc(k);
    t[k]:=fp[i]
   end
  else
   begin
    case sgn[i] of
     '+' : t[k-1]:=t[k-1]+t[k];
     '-' : t[k-1]:=t[k-1]-t[k];
     '*' : t[k-1]:=t[k-1]*t[k];
     '/' : t[k-1]:=t[k-1] div t[k]
    end;
    dec(k)
   end
 end;
writeln(t[1]);
close(input);
close(output)
end.