Cod sursa(job #3301280)

Utilizator mihai.25Calin Mihai mihai.25 Data 23 iunie 2025 18:08:59
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <fstream>

#include <string>

#include <stack>

using namespace std;

ifstream fin ("evaluare.in");

ofstream fout ("evaluare.out");

int prioritate (char op) {

	if (op == '+' || op == '-')
		return 1;
	
	if (op == '*' || op == '/')
		return 2;

	return 0;
}

int aplica_op (int a, int b, char op) {

	switch (op) {

		case '+':	return a + b;
					break;

		case '-':	return a - b;
					break;

		case '*':	return a * b;
					break;

		case '/':	return a / b;
					break;
	}

	return 0;
}

int evalueaza_expresie (string & expr) {

	stack <int> valori;

	stack <char> operatori;

	int i = 0, n = expr.size ();

	while (i < n) {

		if (isdigit (expr[i])) {

			int nr = 0;

			while (i < n && isdigit (expr[i])) {

				nr = nr * 10 + (expr[i] - '0');

				i++;
			}

			valori.push (nr);
		}
		else {

			if (expr[i] == '(') {

				operatori.push ('(');

				i++;
			}
			else {

				if (expr[i] == ')') {

					while (!operatori.empty () && operatori.top () != '(') {

						int b = valori.top (); valori.pop ();

						int a = valori.top (); valori.pop ();

						char op = operatori.top (); operatori.pop ();

						valori.push (aplica_op (a, b, op));
					}

					if (!operatori.empty ())
						operatori.pop ();

					i++;
				}
				else {

					while (!operatori.empty () && prioritate (operatori.top ()) >= prioritate (expr[i])) {

						int b = valori.top (); valori.pop ();

						int a = valori.top (); valori.pop ();

						char op = operatori.top (); operatori.pop ();

						valori.push (aplica_op (a, b, op));
					}

					operatori.push (expr[i]);

					i++;
				}
			}
		}
	}

	while (!operatori.empty ()) {

		int b = valori.top (); valori.pop ();

		int a = valori.top (); valori.pop ();

		char op = operatori.top (); operatori.pop ();

		valori.push (aplica_op (a, b, op));
	}

	return valori.top ();
}

int main () {

	string expresie;

	fin >> expresie;

	fout << evalueaza_expresie (expresie);

	return 0;
}