Pagini recente » Cod sursa (job #656704) | Cod sursa (job #440573) | info-arena 2.0 | Cod sursa (job #1563697) | Cod sursa (job #1199187)
#include <iostream>
#include <cstdio>
#include <stack>
#include <unordered_map>
#include <cctype>
using namespace std;
int apply(char op, int x, int y)
{
switch (op) {
case '+': return x+y;
case '-': return x-y;
case '*': return x*y;
case '/': return x/y;
default: return 0;
}
}
void reduce(stack<char>& ops, stack<int>& nums)
{
char op = ops.top();
ops.pop();
int num = nums.top();
nums.pop();
nums.top() = apply(op, nums.top(), num);
}
int main()
{
ios::sync_with_stdio(false);
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
unordered_map<char, int> precedence = {{'(', 0}, {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
stack<char> ops;
ops.push('(');
stack<int> nums;
bool finish = false;
while (!finish) {
char c = cin.get();
if (c == '\n') {
c = ')';
finish = true;
}
if (isdigit(c)) {
cin.unget();
int num;
cin >> num;
nums.push(num);
}
else {
if (c == '(') {
ops.push(c);
}
else if (c == ')') {
while (ops.top() != '(') {
reduce(ops, nums);
}
ops.pop();
}
else {
while (precedence[ops.top()] >= precedence[c]) {
reduce(ops, nums);
}
ops.push(c);
}
}
}
printf("%d\n", nums.top());
return 0;
}