Cod sursa(job #3310972)

Utilizator pctirziuTirziu Petre pctirziu Data 18 septembrie 2025 13:41:51
Problema Evaluarea unei expresii Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.49 kb
#include <fstream>
#include <stack>

using namespace std;

ifstream cin("evaluare.in");
ofstream cout("evaluare.out");

int apply(char op, int num1, int num2)
{
    if (op == '+')
        return num1 + num2;
    else if (op == '-')
        return num1 - num2;
    else if (op == '*')
        return num1 * num2;
    else
        return num1 / num2;
}

int precedence(char ch)
{
    if (ch == '+' or ch == '-')
        return 1;
    return 2;
}

int main()
{

    string s;
    cin >> s;

    stack<int> nums;
    stack<char> ops;

    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == ' ')
            continue;
        if (isdigit(s[i]))
        {
            int num = 0;
            while (i < s.size() and isdigit(s[i]))
            {
                num = num * 10 + s[i] - '0';
                i++;
            }
            i--;
            nums.push(num);
        }
        else if (s[i] == '(')
            ops.push('(');
        else if (s[i] == '+' or s[i] == '-')
        {
            if(i == 0 or s[i - 1] == '(')
                nums.push(0);
            while (!ops.empty() and ops.top() != '(' and precedence(ops.top()) == 2)
            {
                int b = nums.top();
                nums.pop();
                int a = nums.top();
                nums.pop();
                nums.push(apply(ops.top(), a, b));
                ops.pop();
            }
            ops.push(s[i]);
        }
        else if (s[i] == '*' or s[i] == '/')
        {
            while (!ops.empty() and ops.top() != '(' and precedence(ops.top()) == 2)
            {
                int b = nums.top();
                nums.pop();
                int a = nums.top();
                nums.pop();
                nums.push(apply(ops.top(), a, b));
                ops.pop();
            }
            ops.push(s[i]);
        }
        else
        {
            while (!ops.empty() and ops.top() != '(')
            {
                int b = nums.top();
                nums.pop();
                int a = nums.top();
                nums.pop();
                nums.push(apply(ops.top(), a, b));
                ops.pop();
            }
            ops.pop();
        }
    }
    while (!ops.empty() and ops.top() != '(')
    {
        int b = nums.top();
        nums.pop();
        int a = nums.top();
        nums.pop();
        nums.push(apply(ops.top(), a, b));
        ops.pop();
    }

    cout << nums.top();
    return 0;
}