Cod sursa(job #805502)

Utilizator mlupseLupse-Turpan Mircea mlupse Data 31 octombrie 2012 16:11:54
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
using namespace std;
#include<fstream>
#include<ctype.h>
#include<cstring>
#include<stdlib.h>
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char x[200001],polo[200001],st[200001],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;
}