Pagini recente » Cod sursa (job #901806) | Borderou de evaluare (job #135280) | Cod sursa (job #39280) | Cod sursa (job #1799855) | Cod sursa (job #1445755)
#include <iostream>
#include <cassert>
#include <stack>
#include <string>
using namespace std;
#define _submit
#ifdef _submit
#define InFile "evaluare.in"
#define OutFile "evaluare.out"
#else
#define InFile "fis.in"
#define OutFile "fis.out"
#endif
string expression;
stack<int> operands;
class jmenstack {
private:
stack<char> S;
public:
void push(char c) {
S.push(c);
}
char top() {
return S.top();
}
void pop() {
int op1, op2;
char c = S.top();
S.pop();
switch (c) {
case '+':
op1 = operands.top();
operands.pop();
op2 = operands.top();
operands.pop();
operands.push(op1 + op2);
break;
case '-':
op1 = operands.top();
operands.pop();
op2 = operands.top();
operands.pop();
operands.push(op1 - op2);
break;
case '*':
op1 = operands.top();
operands.pop();
op2 = operands.top();
operands.pop();
operands.push(op1 * op2);
break;
case '/':
op1 = operands.top();
operands.pop();
op2 = operands.top();
operands.pop();
operands.push(op1 / op2);
break;
default:
break;
}
}
bool empty() {
return S.empty();
}
} tokens;
int main() {
assert(freopen(InFile, "r", stdin));
assert(freopen(OutFile, "w", stdout));
cin >> expression;
for (auto i = expression.rbegin(); i != expression.rend(); i++) {
switch (*i) {
case ')':
tokens.push(*i);
break;
case '(':
while (tokens.top() != ')')
tokens.pop();
tokens.pop();
break;
case '+':
case '-':
while (!tokens.empty() && (tokens.top() == '*' || tokens.top() == '/'))
tokens.pop();
tokens.push(*i);
break;
case '*':
case '/':
tokens.push(*i);
break;
default:
int nr = 0;
int p = 1;
auto lasti = i;
while (i != expression.rend() && *i <= '9' && *i >= '0') {
nr += p * ((*i) - '0');
p *= 10;
lasti = i;
i++;
}
i = lasti;
operands.push(nr);
break;
}
}
while (!tokens.empty())
tokens.pop();
assert(operands.size() == 1);
cout << operands.top() << '\n';
return 0;
}