Pagini recente » Cod sursa (job #2775481) | Cod sursa (job #2866121) | Cod sursa (job #1879895) | Cod sursa (job #3134056) | Cod sursa (job #2282548)
#include <bits/stdc++.h>
using namespace std;
int prec (char c)
{
if (c == '-' or c == '+')
return 1;
return 2;
}
bool isOp (char c)
{
return c == '+' or c == '-' or c == '*' or c == '/';
}
bool isDigit (char c)
{
return c >= '0' and c <= '9';
}
int execute (int a, char c, int b)
{
if (c == '+') return a + b;
else if (c == '-') return a - b;
else if (c == '*') return a * b;
else if (c == '/') return a / b;
else assert(0);
}
ifstream input ("evaluare.in");
ofstream output("evaluare.out");
int main() {
string s;
input >> s;
stack <char> operators;
stack <int> values;
for (int index = 0; index < (int)s.size(); ++ index)
{
auto &elem = s[index];
if (elem == '(')
operators.push(elem);
else if (elem == ')')
{
if (operators.top() == '(')
operators.pop();
else
{
while (operators.top() != '(') {
int top1 = values.top();
values.pop();
int top2 = values.top();
values.pop();
values.push(execute(top2, operators.top(), top1));
operators.pop();
}
assert(operators.top() == '(');
operators.pop();
}
}
else if (isOp(elem))
{
if (values.empty())
goto jump;
while (operators.size() and isOp(operators.top()) and prec(operators.top()) >= prec(elem))
{
int top1 = values.top();
values.pop();
int top2 = values.top();
values.pop();
values.push(execute(top2, operators.top(), top1));
operators.pop();
}
operators.push(elem);
}
else
{
jump:
bool minus = false;
if (elem == '-') {
minus = true;
index += 1;
}
assert(isDigit(s[index]));
int number = 0;
while (index < (int)s.size() and isDigit(s [index]))
{
number = number * 10 + s[index] - '0';
index += 1;
}
if (index < (int)s.size()) index -= 1;
if (minus) number = -number;
values.push(number);
}
}
while (operators.size())
{
int top1 = values.top(); values.pop();
int top2 = values.top(); values.pop();
values.push(execute(top2, operators.top(), top1));
operators.pop();
}
assert(values.size() == 1);
output << values.top() << '\n';
return 0;
}