Pagini recente » Cod sursa (job #2756632) | Monitorul de evaluare | Cod sursa (job #2254984) | Cod sursa (job #2823166) | Cod sursa (job #1371872)
#include <cstdio>
#include <cctype>
#include <stack>
using namespace std;
char exp[100005];
stack <int> polsky;
stack <char> op;
void open_file()
{
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
}
void read()
{
fgets(exp, 100005, stdin);
}
void aplicare_semn(char semn)
{
int first = polsky.top();
polsky.pop();
int second = polsky.top();
polsky.pop();
switch(semn)
{
case '+': polsky.push(first+second); break;
case '-': polsky.push(second-first); break;
case '*': polsky.push(first*second); break;
case '/': polsky.push(second/first); break;
}
//printf("%c %d %d\n", semn, first, second);
}
void solve()
{
for(int i = 0; exp[i] != '\0'; ++i)
{
if(isdigit(exp[i]))
{
int x = 0;
while(isdigit(exp[i]))
{
x = x*10+exp[i]-'0';
++i;
}
polsky.push(x);
--i;
}
else
{
if(exp[i] == '+')
{
if(!op.empty() && (op.top() == '*' || op.top() == '/' || op.top() == '+' || op.top() == '-'))
{
aplicare_semn(op.top());
op.pop();
}
op.push('+');
}
if(exp[i] == '-')
{
if(!op.empty() && (op.top() == '*' || op.top() == '/' || op.top() == '+' || op.top() == '-'))
{
aplicare_semn(op.top());
op.pop();
}
op.push('-');
}
if(exp[i] == '*')
{
if(!op.empty() && (op.top() == '*' || op.top() == '/'))
{
aplicare_semn(op.top());
op.pop();
}
op.push('*');
}
if(exp[i] == '/')
{
if(!op.empty() && (op.top() == '*' || op.top() == '/'))
{
aplicare_semn(op.top());
op.pop();
}
op.push('/');
}
if(exp[i] == '(')
{
op.push('(');
}
if(exp[i] == ')')
{
while(op.top() != '(')
{
aplicare_semn(op.top());
op.pop();
}
op.pop();
}
}
}
while(!op.empty())
{
aplicare_semn(op.top());
op.pop();
}
}
void print()
{
printf("%d", polsky.top());
}
int main()
{
open_file();
read();
solve();
print();
return 0;
}