Cod sursa(job #184705)

Utilizator me_andyAvramescu Andrei me_andy Data 24 aprilie 2008 09:39:37
Problema Evaluarea unei expresii Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include<fstream.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char x[100001],polo[100001],st[100001],op[]="+-*/()",c;
int n,i,k,vf=-1,l;
int y,st2[100001];
char pop()
{
if (vf>=0) return st[vf--];
return 0;
}
void push(char c)
{
st[++vf]=c;
}
int main()
{
 fin.getline(x,100000);
 n=strlen(x);
 for(i=0;i<n;i++)
{
 if(!strchr(op,x[i]))
 {while(!strchr(op,x[i+1]))
 {  polo[k++]=x[i];i++;}
   polo[k++]=x[i];
   polo[k++]='>';
 }
else
 switch (x[i])
 {
 case '(': push(x[i]);break;
 case ')': while((c=pop())!='(') polo[k++]=c;break;
 case '*': case '/':
 if( strchr("(+-",st[vf]) || (vf==-1)) push(x[i]);
 else
 if( strchr("*/",st[vf]) ) {polo[k++]=pop();i--;}break;
 case '+': case '-':
 if( st[vf]=='('|| (vf==-1) ) push(x[i]);
 else
 {polo[k++]=pop();i--;}
 }
}
while((c=pop())!=0) polo[k++]=c;
polo[k++]=0;
 n=strlen(polo);
 l=-1;
 for(i=0;i<n;i++)
 {
 vf=0;
 st[0]=0;
 while(isdigit(polo[i]))
  st[vf++]=polo[i++];
 if (polo[i]=='>')
  {
  st[vf]=0;
  st2[++l]=atoi(st);
  }
  switch(polo[i])
  { case '*':st2[l-1]=st2[l-1]*st2[l--];break;
    case '+':st2[l-1]=st2[l-1]+st2[l--]; break;
    case '-':st2[l-1]=st2[l-1]-st2[l--]; break;
    case '/':st2[l-1]=st2[l-1]/st2[l--];break;
  }
 }
fout<<st2[0];
return 0;
}