Cod sursa(job #157659)

Utilizator FlorinC1996Florin C FlorinC1996 Data 13 martie 2008 10:31:13
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.47 kb
#include<stdio.h>   
#include<stdlib.h>   
#include<string.h>   
#include<ctype.h>   
FILE*f=fopen("evaluare.in","r");   
FILE*g=fopen("evaluare.out","w");   
char s[100000][11];   
char st[100000/2];   
char rez[100000][11];   
int n;    
void read()   
 {   
  char x,y;   
  int p;   
  y='!';   
  p=0;   
  while(!feof(f))   
   {   
   fscanf(f,"%c",&x);   
   if(x!='\n') {++n;   
   if(isdigit(y) && isdigit(x)) { n--;++p;}   
   else p=0;   
   s[n][p]=x;   
   y=x;         }   
   }   
  
 }   
void poloneza()   
 {   
 int i,k,vf=0;   
 st[0]='!';   
 k=0;   
 for(i=1;i<=n;++i)   
  {   
   if(s[i][0]=='+' || s[i][0]=='-')   
      {   
      while(st[vf]=='*' || st[vf]=='/' || st[vf]=='-' || st[vf]=='+')   
       {   
       rez[k++][0]=st[vf];   
       --vf;   
       }   
      st[++vf]=s[i][0];   
      }   
   else if(s[i][0]=='(') st[++vf]='(';   
   else if (s[i][0]==')')   
     {   
       //copiez in rez toti operanzii pana la ).   
       while(st[vf]!='(')   
     {   
      rez[k++][0]=st[vf];   
      --vf;   
     }   
       --vf; //sterg '(';   
     }   
   else  
    if (s[i][0]=='*' || s[i][0]=='/')   
      {   
      while(st[vf]=='*' || st[vf]=='/')   
       {   
       rez[k++][0]=st[vf];   
       --vf;   
       }   
      st[++vf]=s[i][0];   
      }   
   else  
     {   
     strcpy(rez[k++],s[i]);   
     }   
  }   
 while(st[vf]!='!')   
  {   
  rez[k++][0]=st[vf];   
  vf--;   
  }   
 n=k;   
  
 }   
void itoap(int x, char a[])   
 {   
 int i=0,k=0;   
 char b[12];   
 if(x<0) k=1,a[0]='-',x*=(-1);   
 if(x==0) k=1,a[0]='0';   
 while(x)   
  {   
  b[i++]=x%10+'0';   
  x/=10;   
  }   
 int j;   
 for(j=0;j<i;++j)   
  {   
  a[j+k]=b[i-j-1];   
  }   
 a[i+k]=NULL;   
 }   
void eval()   
 {   
 int x,y,i,vf=-1;   
 char st[100000/2][11];   
 for(i=0;i<n;++i)   
  {   
  if(rez[i][0]=='+' || rez[i][0]=='-' || rez[i][0]=='*' || rez[i][0]=='/')   
    {   
     x=atoi(st[vf]);   
     --vf;   
     y=atoi(st[vf]);   
     switch(rez[i][0])   
      {   
      case '+': itoap(x+y,st[vf]); break;   
      case '-': itoap(y-x,st[vf]); break;   
      case '*': itoap(x*y,st[vf]); break;   
      case '/': itoap(y/x,st[vf]); break;   
      }   
    }   
  else  
   strcpy(st[++vf],rez[i]);   
  }   
 fprintf(g,"%s\n",st[0]);   
 }   
int main()   
 {   
 read();   
 poloneza();   
 eval();   
 return 0;   
 }