Cod sursa(job #770552)

Utilizator Victor10Oltean Victor Victor10 Data 23 iulie 2012 13:27:26
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <cstdio>
#include <stack>
#include <cctype>
#include <cstring>
#define MAX 1000000000
using namespace std;

stack <int> ops;

char cit [100005];
int out [100005], rez [100005];

int chartoint (int &start) {
	int nr = 0;
	for (; isdigit (cit [start]); ++ start)
		nr = nr * 10 + (cit [start] - '0');
	return nr;
}

int prior (char c1) {
	if (c1 == '*' || c1 == '/') return 2;
	if (c1 == '+' || c1 == '-') return 1;
	if (c1 == '(') return 0;
}

int oper (char c1) {
	if (c1 == '*') return 4;
	if (c1 == '/') return 3;
	if (c1 == '+') return 2;
	if (c1 == '-') return 1;
}

int main () {
	
	freopen ("evaluare.in", "r", stdin);
	freopen ("evaluare.out", "w", stdout);
	
	int i, sz = 0, dimrez = 0;
	
	fgets (cit, 100002, stdin);
	
	for (i = 0; cit [i + 1] != NULL; ++ i) {
		if (isdigit (cit [i])) {
			out [++ sz] = chartoint (i);
			-- i;
			continue;
		}
		else if (cit [i] != '(' && cit [i] != ')') {
			while (ops . size () && prior (ops . top ()) >= prior (cit [i])) {
				out [++ sz] = MAX + oper (ops. top ());
				ops . pop ();
			}
			ops . push (cit [i]);
		}
		else if (cit [i] == '(')
			ops . push ('(');
		else if (cit [i] == ')') {
			while (ops . top () != '(') {
				out [++ sz] = MAX + oper (ops . top ());
				ops . pop ();
			}
			ops . pop ();
		}
	}
	while (ops . size ()) {
		out [++ sz] = MAX + oper (ops . top ());
		ops . pop ();
	}
	
	for (i = 1; i <= sz; ++ i) {
		if (out [i] <= MAX)
			rez [++ dimrez] = out [i];
		if (out [i] == MAX + 1) rez [dimrez - 1] -= rez [dimrez --];
		if (out [i] == MAX + 2) rez [dimrez - 1] += rez [dimrez --];
		if (out [i] == MAX + 3) rez [dimrez - 1] /= rez [dimrez --];
		if (out [i] == MAX + 4) rez [dimrez - 1] *= rez [dimrez --];
	}
	
	printf ("%d\n", rez [1]);
}