Pagini recente » Cod sursa (job #2546567) | Cod sursa (job #2281651) | Cod sursa (job #2721678) | Cod sursa (job #1089750) | Cod sursa (job #1570137)
#include <cstdio>
#include <cstring>
#include <stack>
#define NMAX 100000
using namespace std;
char s[NMAX+10],post[2*NMAX+10],semn[NMAX+10];
int i,n,ord[50],crt,crtp,val;
stack <int> rez;
void init()
{
ord[')']=1;
ord['+']=2;
ord['-']=2;
ord['*']=3;
ord['/']=3;
ord['(']=4;
}
int slv(int a,int b,char op)
{
if(op=='+') return a+b;
if(op=='-') return a-b;
if(op=='*') return a*b;
if(op=='/') return a/b;
}
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
gets(s);
n=strlen(s);
s[n]=')';
semn[++crt]='(';
init();
while(i<=n)
{
if(s[i]<'0' || s[i]>'9')
{
while(ord[s[i]]<=ord[semn[crt]] && semn[crt]!='(')
{
post[++crtp]=semn[crt--];
post[++crtp]=',';
}
if(s[i]==')')
--crt;
else semn[++crt]=s[i];
++i;
}
else
{
while(s[i]>='0'&&s[i]<='9')
post[++crtp]=s[i++];
post[++crtp]=',';
}
}
i=1;
while(i<=crtp)
{
int nr=0;
if(post[i]<'0' || post[i]>'9')
{
val=rez.top();
rez.pop();
rez.top()=slv(rez.top(),val,post[i]);
++i;
}
else
{
while(post[i]>='0' && post[i]<='9')
nr=nr*10+post[i++]-'0';
rez.push(nr);
}
i++;
}
printf("%d\n",rez.top());
return 0;
}