Cod sursa(job #1199200)

Utilizator howsiweiHow Si Wei howsiwei Data 18 iunie 2014 15:58:08
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#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}};
	string expr;
	getline(cin, expr);
	expr = '('+expr+')';
	stack<char> ops;
	stack<int> nums;
	for (auto it = expr.begin(); it != expr.end(); ) {
		if (isdigit(*it)) {
			int num = 0;
			do {
				num = num*10+*it-'0';
				++it;
			} while (isdigit(*it));
			nums.push(num);
		}
		else {
			if (*it == '(') {
				ops.push(*it);
			}
			else if (*it == ')') {
				while (ops.top() != '(') {
					reduce(ops, nums);
				}
				ops.pop();
			}
			else {
				while (precedence[ops.top()] >= precedence[*it]) {
					reduce(ops, nums);
				}
				ops.push(*it);
			}
			++it;
		}
	}
	printf("%d\n", nums.top());
	return 0;
}