Cod sursa(job #2607534)

Utilizator Arteni_CristiArteni Cristi Arteni_Cristi Data 29 aprilie 2020 21:20:18
Problema Evaluarea unei expresii Scor 70
Compilator fpc Status done
Runda Arhiva educationala Marime 1.95 kb
var st,t:array[0..100005] of int64;
    sgn,sg:array[0..100005] of char;
    n,i,k,a,q:longint;
    s:string;

//st[] stiva finala de calcul
//t[] retinerea numerelor
//sg[] stiva de retinere a numerelor in functie de prioritate  ()__0   +-__1  */__2
//k contorul pentru sg[]
//sgn[] stiva finala a semnelor in ordine corecta
//n contorul pentru st[] si sgn[] impreuna

{ Exemplu :   (1+1)*13*10/2  --> 1 1 + 13 * 10 2 / +

  n=9

  t[]     1    1   ___  13   ___  10   2   ___  ___
  sgn[]  ___  ___   +   ___   *   ___  ___  /    +
}

begin
assign(input,'evaluare.in'); reset(input);
assign(output,'evaluare.out'); rewrite(output);
readln(s);
for i:=1 to length(s) do
 begin
  if pos(s[i],'0123456789')<>0 then
   begin
    a:=a*10+ord(s[i])-48;
    if (i=length(s)) or (pos(s[i+1],'0123456789')=0) then
     begin
      inc(n);
      t[n]:=a;
      a:=0
     end
   end else
  if s[i]='(' then begin inc(k); sg[k]:='(' end else
  if (s[i]='*') or (s[i]='/') then
   begin
    inc(k); sg[k]:=s[i];
    while (sg[k-1]='*') or (sg[k-1]='/') do
     begin
      inc(n); sgn[n]:=sg[k-1];
      sg[k-1]:=sg[k];
      dec(k)
     end
   end else
  if (s[i]='+') or (s[i]='-') then
   begin
    inc(k); sg[k]:=s[i];
    while pos(sg[k-1],'+-/*')<>0 do
     begin
      inc(n); sgn[n]:=sg[k-1];
      sg[k-1]:=sg[k];
      dec(k)
     end
   end else
  if s[i]=')' then
   begin
    while (k>0) and (sg[k]<>'(') do
     begin
      inc(n); sgn[n]:=sg[k];
      dec(k)
     end;
    dec(k)
   end
 end;
if k>0 then for i:=k downto 1 do
 begin
  inc(n);
  sgn[n]:=sg[i]
 end;
q:=0;
for i:=1 to n do
 if pos(sgn[i],'+-*/')=0 then
  begin
   inc(q);
   st[q]:=t[i]
  end
 else
  begin
   case sgn[i] of
    '+' : st[q-1]:=st[q-1]+st[q];
    '-' : st[q-1]:=st[q-1]-st[q];
    '*' : st[q-1]:=st[q-1]*st[q];
    '/' : st[q-1]:=st[q-1] div st[q]
   end;
   dec(q)
  end;
writeln(st[1]);
close(input);
close(output)
end.