Cod sursa(job #3286240)

Utilizator herbiHreban Antoniu George herbi Data 13 martie 2025 20:59:59
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <iostream>
#include <fstream>
#include <stack>

using namespace std;

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

bool is_op(char c)
{
    return c == '+' || c == '-' || c == '*' || c == '/';
}

int priority(char op)
{
    if (op == '+' || op == '-')
        return 1;
    if (op == '*' || op == '/')
        return 2;
    return -1;
}

void process_op(stack<int>& st, char op)
{
    int r = st.top();
    st.pop();
    int l = st.top();
    st.pop();
    switch (op)
    {
    case '+':
        st.push(l + r);
        break;
    case '-':
        st.push(l - r);
        break;
    case '*':
        st.push(l * r);
        break;
    case '/':
        st.push(l / r);
        break;
    }
}

int evaluate(string& s)
{
    stack<int> st;
    stack<char> op;
    for (int i = 0; i < (int)s.size(); i++)
    {
        if (s[i] == '(')
        {
            op.push('(');
        }
        else if (s[i] == ')')
        {
            while (op.top() != '(')
            {
                process_op(st, op.top());
                op.pop();
            }
            op.pop();
        }
        else if (is_op(s[i]))
        {
            char cur_op = s[i];
            while (!op.empty() && priority(op.top()) >= priority(cur_op))
            {
                process_op(st, op.top());
                op.pop();
            }
            op.push(cur_op);
        }
        else
        {
            int number = 0;
            while (i < (int)s.size() && isalnum(s[i]))
                number = number * 10 + s[i++] - '0';
            --i;
            st.push(number);
        }
    }

    while (!op.empty())
    {
        process_op(st, op.top());
        op.pop();
    }
    return st.top();
}

int main()
{
    string s;
    fin >> s;
    fout << evaluate(s) << "\n";
    return 0;
}