Pagini recente » Cod sursa (job #274168) | Cod sursa (job #3203925) | Cod sursa (job #1896495) | Cod sursa (job #2736627) | Cod sursa (job #1637530)
#include <fstream>
#include <stack>
#define pl 1000000001
#define mn 1000000002
#define inm 1000000003
#define imp 1000000004
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char s[100001];
int a[100001],n;
inline int P(char c)
{if(c=='+'||c=='-')return 1;
else return 2;
}
void Poloneza()
{stack <char> ST;
int i,nr;
char c;
for(i=0;s[i]!=0;i++)
{if(s[i]=='(')ST.push(s[i]);
if(s[i]>='0'&&s[i]<='9')
{nr=0;
while(s[i]>='0'&&s[i]<='9')
{nr=nr*10+s[i]-'0';
i++;
}
i--;a[n]=nr;n++;
}
else if(s[i]==')')
{while(ST.size()>0&&ST.top()!='(')
{c=ST.top();
if(c=='+')a[n++]=pl;
else if(c=='-')a[n++]=mn;
else if(c=='*')a[n++]=inm;
else if(c=='/')a[n++]=imp;
ST.pop();
}
ST.pop();
}
else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')
{if(ST.size()==0)ST.push(s[i]);
else if(ST.top()=='(')ST.push(s[i]);
else {while(ST.size()>0&&P(ST.top())>P(s[i])) {c=ST.top();
if(c=='+')a[n++]=pl;
else if(c=='-')a[n++]=mn;
else if(c=='*')a[n++]=inm;
else if(c=='/')a[n++]=imp;
ST.pop();
}
ST.push(s[i]);
}
}
}
while(ST.size()>0){c=ST.top();
if(c=='+')a[n++]=pl;
else if(c=='-')a[n++]=mn;
else if(c=='*')a[n++]=inm;
else if(c=='/')a[n++]=imp;
ST.pop();
}
}
int Evaluare()
{stack <int>ST;
int x,y,v,i;
for(i=0;i<n;i++)
{//fout<<a[i]<<" ";
if(a[i]<=1000000000) ST.push(a[i]);
else{x=ST.top();ST.pop();
y=ST.top();ST.pop();
if(a[i]==pl)v=x+y;
if(a[i]==mn)v=y-x;
if(a[i]==inm)v=y*x;
if(a[i]==imp)
if(x!=0)v=y/x;
else v=0;
ST.push(v);
}
}
return ST.top();
}
int main()
{int i;
fin>>s;
Poloneza();
fout<<Evaluare();
}