Cod sursa(job #2931523)

Utilizator matthriscuMatt . matthriscu Data 31 octombrie 2022 12:16:21
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>
using namespace std;

int main() {
    ifstream fin("evaluare.in");
    ofstream fout("evaluare.out");

    string expression;
	fin >> expression;

	stack<int> terms;
	stack<char> operations;

	auto priority = [](char op) {
		if (op == '*' || op == '/')
			return 2;
		if (op == '+' || op == '-')
			return 1;
		return 0;
	};

	auto compute = [&]() {
		int n2 = terms.top();
		terms.pop();

		int n1 = terms.top();
		terms.pop();

		if (operations.top() == '*')
			terms.push(n1 * n2);
		else if (operations.top() == '/')
			terms.push(n1 / n2);
		else if (operations.top() == '+')
			terms.push(n1 + n2);
		else if (operations.top() == '-')
			terms.push(n1 - n2);

		operations.pop();
	};

	for (size_t i = 0; i < expression.size(); ++i)
		if (expression[i] == '(')
			operations.push('(');
		else if (expression[i] == ')') {
			while (operations.top() != '(')
				compute();
			operations.pop();
		} else if (priority(expression[i])) {
			while (!operations.empty() && priority(operations.top()) >= priority(expression[i]))
				compute();
			operations.push(expression[i]);
		} else if (isdigit(expression[i])) {
			int n = 0;
			while (isdigit(expression[i]))
				n = 10 * n + expression[i++] - '0';
			--i;
			terms.push(n);
		}

	while (!operations.empty())
		compute();
	
	fout << terms.top() << '\n';
}