Cod sursa(job #3242463)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 12 septembrie 2024 12:39:09
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
// polish form

#include <fstream>
#include <string>
#include <stack>

int main()
{
    std::ifstream cin("evaluare.in");
    std::ofstream cout("evaluare.out");

    std::string expr;
    cin >> expr;

    std::stack<int> values;
    std::stack<char> operators;

    auto perform_op = [&]()
    {
        int b = values.top();
        values.pop();
        int a = values.top();
        values.pop();
        char op = operators.top();
        operators.pop();

        if (op == '+')
            values.push(a + b);
        else if (op == '-')
            values.push(a - b);
        else if (op == '*')
            values.push(a * b);
        else if (op == '/')
            values.push(a / b);
        else
            throw "Unknown operator";
    };

    auto precedence = [](char c)
    {
        if (c == '+' || c == '-')
            return 1;
        if (c == '*' || c == '/')
            return 2;
        if (c == '(')
            return -1; // should never perform_op when the top of the operator stack is '('
        throw "Unknown operator";
    };

    for (int i = 0; i < (int)expr.size(); i++)
    {
        if (isdigit(expr[i])) // number
        {
            int number = 0;
            while (i < (int)expr.size() && isdigit(expr[i]))
            {
                number = number * 10 + (expr[i] - '0');
                ++i;
            }

            --i; // for loop will increment i
            values.push(number);
        }
        else if (expr[i] == '(') // open subexpression
        {
            operators.push('(');
        }
        else if (expr[i] == ')') // close subexpression
        {
            while (operators.top() != '(')
                perform_op();
            operators.pop(); // pop open parentheses
        }
        else // operator
        {
            while (!operators.empty() && precedence(operators.top()) >= precedence(expr[i]))
                perform_op();
            operators.push(expr[i]);
        }
    }

    while (!operators.empty())
        perform_op();

    cout << values.top() << '\n';

    return 0;
}