Cod sursa(job #1199090)

Utilizator howsiweiHow Si Wei howsiwei Data 18 iunie 2014 08:32:15
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <iostream>
#include <cstdio>
#include <stack>
#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);
	stack<char> ops;
	stack<int> nums;
	ops.push('(');
	bool finish = false;
	while (!finish) {
		char c;
		if (cin.eof()) {
			c = ')';
			finish = true;
		}
		else {
			c = cin.get();
		}
		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 if (c == '+' or c == '-') {
				while (ops.top() != '(') {
					reduce(ops, nums);
				}
				ops.push(c);
			}
			else if (c == '*' or c == '/') {
				while (ops.top() == '*' or ops.top() == '/') {
					reduce(ops, nums);
				}
				ops.push(c);
			}
		}
	}
	printf("%d\n", nums.top());
	return 0;
}