Cod sursa(job #979303)

Utilizator BogdacutuSeniuc Bogdan Bogdacutu Data 1 august 2013 11:04:19
Problema Evaluarea unei expresii Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <stack>

using namespace std;

stack<string> polish, out, aux;
stack<int> num;
map<string, int> operators;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string expr, token;
bool lastNum = false;
char current;
int result, a, b;

int main() {
	fin>>expr;
	operators["+"] = 0;
	operators["-"] = 0;
	operators["/"] = 5;
	operators["*"] = 5;
	for (unsigned int i = 0; i < expr.length(); ++i) {
		current = expr.at(i);
		if (current >= '0' && current <= '9') {
			if (lastNum) {
				string num = out.top();
				out.pop();
				out.push(num+current);
			} else {
				out.push(string(1, current));
				lastNum = true;
			}
		} else {
			if (operators.find(string(1, current)) != operators.end()) {
				while (!aux.empty() && (operators.find(aux.top()) != operators.end())) {
					if (operators[string(1, current)] - operators[aux.top()] <= 0) {
						out.push(aux.top());
						aux.pop();
						continue;
					}
					break;
				}
				aux.push(string(1, current));
			} else if (current == '(') {
				aux.push(string(1, current));
			} else if (current == ')') {
				while (!aux.empty() && aux.top() != "(") {
					out.push(aux.top());
					aux.pop();
				}
				aux.pop();
			}
			lastNum = false;
		}
	}
	while (!aux.empty()) {
		out.push(aux.top());
		aux.pop();
	}
	while (!out.empty()) {
		polish.push(out.top());
		out.pop();
	}
	while (!polish.empty()) {
		token = polish.top();
		if (operators.find(token) != operators.end()) {
			current = token.at(0);
			b = num.top();
			num.pop();
			a = num.top();
			num.pop();
			switch (current) {
				case '+':
					result = a + b;
					break;
				case '-':
					result = a - b;
					break;
				case '*':
					result = a * b;
					break;
				case '/':
					result = a / b;
					break;
			}
			num.push(result);
		} else {
			num.push(atoi(token.c_str()));
		}
		polish.pop();
	}
	fout<<num.top()<<"\n";
	return 0;
}