Cod sursa(job #304003)

Utilizator punkistBarbulescu Dan punkist Data 10 aprilie 2009 18:11:33
Problema Evaluarea unei expresii Scor 10
Compilator fpc Status done
Runda Arhiva educationala Marime 2.33 kb
var s:array[-2..100010] of char;
    lstr:longint;
    x:longint;
    f2:text;

procedure Citeste;
 var f:text;
     a:char;
 begin
  assign(f,'evaluare.in');
  reset(f);
  lstr:=0;
  while not eof(f) do
   begin
    lstr:=lstr+1;
    read(f,a);
    s[lstr]:=a;
   end;
  close(f);
  s[-2]:='(';
  s[-1]:='0';
  s[0]:='+';
  lstr:=lstr+1;
  s[lstr]:=')';
 end;

function isdigit(x2:char):boolean;
var e:boolean;
begin
 e:=false;
 if (ord(x2) >= ord('0')) and (ord(x2) <= ord('9')) then e:=true;
 isdigit:=e;
end;

function eval(y:longint):longint;
 var rez,semn,rezp,nr,aux:longint;
     pot:boolean;
     ls:char;
 begin
  rez:=0;
  semn:=1;
  if x > (lstr+1) then s[x]:=')';
  while s[x]<>')' do
   begin
    x:=x+1;
    while s[x]=' ' do x:=x+1;
      if isdigit(s[x]) or (s[x]='(') then {este un nr}
       begin
        nr:=0;ls:='+';
        pot:=true;
        while pot do
         begin
          if x >  lstr then break;
          while s[x]=' ' do x:=x+1;
          if (s[x]='-') or (s[x]='+') or (s[x]=')') then break;
          if s[x]='(' then
           begin
            aux:=eval(x);
            if ls='+' then nr:=nr+aux;
            if ls='-' then nr:=nr-aux;
            if ls='*' then nr:=nr*aux;
            if ls='/' then nr:=nr div aux;
           end;
          if isdigit(s[x]) then
          begin
           rezp:=0;
           while isdigit(s[x]) do
            begin
             rezp:=rezp * 10 + ord(s[x]) - ord('0');
             x:=x+1;
            end;
           if ls='+' then nr:=nr+rezp;
           if ls='-' then nr:=nr-rezp;
           if ls='*' then nr:=nr*rezp;
           if ls='/' then nr:=nr div rezp;
          end;
          if (s[x]='+') or (s[x]='-') or (s[x]=')') then break;
          if s[x]='*' then ls:='*';
          if s[x]='/' then ls:='/';
          if s[x]='(' then
           begin
            if ls='*' then nr:=nr * eval(x);
            if ls='/' then nr:=nr div eval(x);
           end;
          x:=x+1;
         end;
        rez:=rez + nr * semn;
       end
      else  {este un semn}
       begin
        if s[x] = '-' then semn:=-1;
        if s[x] = '+' then semn:=1;
       end;
   end;
  x:=x+1;
  eval:=rez;
 end;

begin
Citeste;
x:=-2;
assign(f2,'evaluare.out');
rewrite(f2);
writeln(f2,eval(x));
close(f2);
end.