Cod sursa(job #1342240)

Utilizator MrWhiteDELETEME MrWhite Data 13 februarie 2015 18:00:24
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>

using namespace std;

long nr[50000], nrI = -1, opI = -1;
char op[50000];

bool isDigit(char c) {
	return ('0' <= c) && (c <= '9');
}

int isOperator(char c)
{
	return ((c == '(') || (c == '+') || (c == '-') || (c == '*') || (c == '/'));
}

int getPriority(char c)
{
	if ((c == '(') || (c == ')')) {
		return 1;
	} else if ((c == '+') || (c == '-')) {
		return 2;
	} else if ((c == '*') || (c == '/')) {
		return 3;
	}
	return 0;
}

long doOp(long a, long b, char op) {
	if (op == '+') {
		return a + b;
	} else if (op == '-') {
		return a - b;
	} else if (op == '*') {
		return a * b;
	} else if (op == '/') {
		return a / b;
	}
	return 0;
}

void eval()
{
	nr[nrI - 1] = doOp(nr[nrI - 1], nr[nrI], op[opI]);
	--nrI;
	--opI;
}

int main()
{
	ifstream fin("evaluare.in");
	ofstream fout("evaluare.out");
	char old_c = 0, c;
	while (fin >> c) {
		if (isDigit(c)) {
			if (!isDigit(old_c)) {
				nr[++nrI] = 0;
			}
			nr[nrI] = (nr[nrI] * 10) + (c - '0');
		} else if (getPriority(c)) {
			if (c == ')') {
				while (op[opI] != '(') {
					eval();
				}
				--opI;
			} else {
				while ((getPriority(c) < getPriority(op[opI])) && (opI > -1)) {
					eval();
				}
				op[++opI] = c;
			}
		}
		old_c = c;
	}	
	while (opI > -1) {
		eval();
	}
	fout << nr[0] << "\n";
	return 0;
}