Pagini recente » Cod sursa (job #3241121) | Cod sursa (job #1578398) | Cod sursa (job #2599719) | Cod sursa (job #1210476) | Cod sursa (job #1652255)
#include <fstream>
#include <stack>
#define N 100001
#define V 1000000000
#define plus V+1
#define minus V+2
#define inm V+3
#define imp V+4
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char t[N];// exp in
int a[N],n; //forma poloneza
void tip(char c)
{
if(c=='+') a[++n]=plus;
if(c=='-') a[++n]=minus;
if(c=='*') a[++n]=inm;
if(c=='/') a[++n]=imp;
}
inline int P( char c) //prioritate semn
{
if(c=='+' || c=='-') return 1;
return 2;
}
void Poloneza()
{
stack<char> S;
char c;
int i=0,nr;
while(t[i]!=0)
{
if(isdigit(t[i]))
{
nr=0;
while(isdigit(t[i]))
{
nr=nr*10+t[i]-'0';
i++;
}
a[++n]=nr;
}
else if(t[i]=='(')
{
S.push(t[i]);
i++;
}
else if(t[i]==')')
{
while(S.top()!='(')
{
c=S.top();
S.pop();
tip(c);
}
S.pop();
i++;
}
else
{
while(!S.empty() && S.top()!='(' && P(S.top())>=P(t[i]))
{
c=S.top();
S.pop();
tip(c);
}
S.push(t[i]);
i++;
}
}
while(!S.empty())
{
c=S.top();
S.pop();
tip(c);
}
}
int Evaluare()
{
stack<int>S;
int i,x,y;
for(i=1; i<=n; i++)
if(a[i]<=V) S.push(a[i]);
else
{
x=S.top();
S.pop();
y=S.top();
S.pop();
if(a[i]==plus) S.push(x+y);
if(a[i]==minus) S.push(y-x);
if(a[i]==inm) S.push(x*y);
if(a[i]==imp) S.push(y/x);
}
return S.top();
}
int main()
{
fin>>t;
Poloneza();
fout<<Evaluare();
return 0;
}