Pagini recente » Cod sursa (job #2125044) | Cod sursa (job #2904770) | Cod sursa (job #2088975) | Cod sursa (job #2298562) | Cod sursa (job #1091448)
#include <fstream>
#include <cstring>
#include <stack>
#define NMAX 100005
using namespace std;
//forma poloneza
FILE* f=freopen("evaluare.in","r",stdin);
FILE* o=freopen("evaluare.out","w",stdout);
char exp[NMAX];
char pol[NMAX*3];
int ind;
stack<char> op;
stack<int> num;
char sign[]="*/-+",l1[]="/*";
void ToPolish()
{
int l=strlen(exp);
for(int i=0;i<l;++i)
{
char c=exp[i];
switch(c)
{
case'+':case'-':
if(!op.empty()&&strchr(sign,op.top()))
{
pol[ind++]=op.top();
pol[ind++]=' ';
op.pop();
}
op.push(c);
break;
case'*':case'/':
if(!op.empty()&&strchr(l1,op.top()))
{
pol[ind++]=op.top();
pol[ind++]=' ';
op.pop();
}
op.push(c);
break;
case'(':
op.push(c);
break;
case')':
while(op.top()!='(')
{
pol[ind++]=op.top();
pol[ind++]=' ';
op.pop();
}
op.pop();
break;
default:
while(i<l&&exp[i]>='0'&&exp[i]<='9')
{
pol[ind++]=exp[i];
i+=1;
}
pol[ind++]=' ';
i-=1;
break;
}
}
while(!op.empty()) {
pol[ind]=op.top();
pol[ind+1]=' ';
ind+=2;
op.pop();
}
}
void Operation(char c)
{
int b=num.top(); num.pop();
int a=num.top(); num.pop();
switch (c)
{
case '+': num.push(a+b); break;
case '-': num.push(a-b); break;
case '*': num.push(a*b); break;
case '/': num.push(a/b); break;
}
}
void Number(char c[])
{
int x=0;
for(int i=0;i<strlen(c);++i)
x=x*10+(c[i]-'0');
num.push(x);
}
void Evaluate()
{
char *p=strtok(pol," ");
while(p)
{
if(strstr(sign,p))
Operation(p[0]);
else
Number(p);
p=strtok(NULL," ");
}
}
int main()
{
scanf("%s",exp);
ToPolish();
Evaluate();
printf("%d",num.top());
return 0;
}