Cod sursa(job #147847)

Utilizator RobytzzaIonescu Robert Marius Robytzza Data 3 martie 2008 17:27:07
Problema Evaluarea unei expresii Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <stdio.h>   
#include <string.h>   
#define MAX 100001
  
char a[MAX];   
int n;   
  
void citire()   
{   
   freopen ("evaluare.in","r",stdin);   
   fgets(a,MAX,stdin);   
   fclose (stdin);   
}   
  
long da(int st,int dr,char s1,char s2)
{
   int num=0;
   for (int i=dr;i>=st;i--)
   {
       if (a[i]==')')
      num++;
       else
     if (a[i]=='(')
	  num--;
     else
       if ((a[i]==s1 || a[i]==s2) && num==0)
	   return i;
   }

  return -1;
}

void paranteza(int &st,int &dr)
{
   int num=0;
   for (int i=dr-1;i>st;i--)
      if (a[i]==')')
     num++;
      else
    if (a[i]=='(')
       num--;
   if (num==0 && a[st]=='(' && a[dr]==')')
   {
       st++;
       dr--;
       return ;
   }
}

long lal (int st,int dr)
{
   long nr=0,kkt=1;
   if (a[st]=='-')
   {
      kkt=-1;
      st++;
   }
  for (int i=st;i<=dr;i++)
       nr=nr*10+(a[i]-'0');
    return nr*kkt;
}

long lol(int st,int dr)
{
  paranteza(st,dr);
  long aux=da(st+1,dr,'+','-');
  if (aux==-1)
     aux=da(st+1,dr,'*','/');
   if (aux==-1)
       return lal(st,dr);
   long S1=lol(st,aux-1),S2=lol(aux+1,dr);
  switch (a[aux])
   {
   case '+': return S1+S2;
   case '-':  return S1-S2;
   case '*': return S1*S2;
   default:  return S1/S2;
   }
}

int main ()
{
   citire();
   n=(a[strlen (a)-1]=='\n')?strlen(a)-2:strlen(a)-1;
   freopen ("evaluare.out","w",stdout);
   printf ("%ld\n",lol(0,n));
   fclose(stdout);
   return 0;
}