Pagini recente » Diferente pentru algoritmiada-2018/clasament-2 intre reviziile 5 si 4 | Cod sursa (job #1831331) | Autentificare | Cod sursa (job #1831345) | Cod sursa (job #3358964)
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
#define all(x) x.begin(), x.end()
#define fs first
#define sc second
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
bool isDigit(char x) {
return ('0' <= x) and (x <= '9');
}
string expr;
stack<int> num;
stack<char> op;
int prioritate(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
int solve(int x, int y, char op) {
if (op == '+') return x + y;
if (op == '-') return x - y;
if (op == '/') return x / y;
if (op == '*') return x * y;
}
int main() {
fin >> expr;
for (int i = 0; i < expr.size(); ++i) {
if (isDigit(expr[i])) {
int val = 0;
while (i < expr.size() and isDigit(expr[i])) {
val = val * 10 + (expr[i] - '0');
++i;
}
--i;
num.push(val);
}
else if (expr[i] == '(') op.push('(');
else if (expr[i] == ')') {
while (op.size() and op.top() != '(') {
int y = num.top(); num.pop();
int x = num.top(); num.pop();
char semn = op.top(); op.pop();
num.push(solve(x, y, semn));
}
op.pop();
}
else {
while (op.size() and prioritate(op.top()) >= prioritate(expr[i])) {
int y = num.top(); num.pop();
int x = num.top(); num.pop();
char semn = op.top(); op.pop();
num.push(solve(x, y, semn));
}
op.push(expr[i]);
}
}
while (op.size()) {
int y = num.top(); num.pop();
int x = num.top(); num.pop();
char semn = op.top(); op.pop();
num.push(solve(x, y, semn));
}
fout << num.top();
}