Pagini recente » Cod sursa (job #1706169) | Cod sursa (job #1368099) | Cod sursa (job #1723817) | Cod sursa (job #3283954) | Cod sursa (job #1884499)
#include<cstdio>
#include<stack>
#include<cstring>
#include<cctype>
using namespace std;
stack <int> rez;
stack <char> op;
char s[100005];
int priority(char semn)
{
int p;
switch(semn)
{
case '+':
case '-': p=1; break;
case '*':
case '/': p=2; break;
}
return p;
}
void calc()
{
int x=rez.top();
rez.pop();
int y=rez.top();
rez.pop();
switch(op.top())
{
case '+': rez.push(x+y); break;
case '-': rez.push(y-x); break;
case '*': rez.push(x*y); break;
case '/': rez.push(y/x); break;
}
op.pop();
}
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
int n,nr,x;
char y;
gets(s);
n=strlen(s);
for(int i=0; i<n; i++)
{
if(!op.empty())
y=op.top();
if(s[i]=='(')
{
op.push('(');
continue;
}
if(isdigit(s[i]))
{
nr=0;
while(i<n && isdigit(s[i]))
{
nr=nr*10+s[i]-'0';
i++;
}
i--;
rez.push(nr);
x=rez.top();
continue;
}
if(s[i]==')')
{
while(!op.empty() && op.top()!='(')
calc();
x=rez.top();
op.pop();
continue;
}
int z=!op.empty();
if(op.empty() || (op.empty() && op.top()=='('))
{
op.push(s[i]);
continue;
}
if(op.empty() || (op.empty() && priority(s[i])>priority(op.top())))
{
op.push(s[i]);
continue;
}
while(!op.empty() && op.top()!='(' && priority(s[i])<=priority(op.top()))
{
calc();
x=rez.top();
}
op.push(s[i]);
}
while(!op.empty())
calc();
printf("%d\n",rez.top());
return 0;
}