Cod sursa(job #2848004)

Utilizator AswVwsACamburu Luca AswVwsA Data 11 februarie 2022 22:27:28
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <stack>
using namespace std;

stack <int> st;
stack <char> polo;

int pr(char op)
{
    switch (op)
    {
    case '+':
    case '-':
        return 1;
    case '*':
    case '/':
        return 2;
    }
}

int op(int x, char oper, int y)
{
    switch (oper)
    {
    case '+':
        return x + y;
    case '-':
        return x - y;
    case '/':
        return x / y;
    case '*':
        return x * y;
    }
}

string s;
int main()
{
    ifstream cin("evaluare.in");
    ofstream cout("evaluare.out");

    cin >> s;
    int nr = 0;
    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] >= '0' and s[i] <= '9')
        {
            nr = nr * 10 + s[i] - '0';
            continue;
        }
        if (nr)
            st.push(nr);
        nr = 0;
        if (s[i] == '(')
        {
            polo.push('(');
            continue;
        }
        if (s[i] == ')')
        {
            int val = st.top();
            st.pop();
            st.top() = op(st.top(), polo.top(), val);
            polo.pop();
            polo.pop();
            continue;
        }
        while (!polo.empty() and pr(s[i]) <= pr(polo.top())
                and polo.top() != '('
              )
        {
            int val = st.top();
            st.pop();
            st.top() = op(st.top(), polo.top(), val);
            polo.pop();
        }
        polo.push(s[i]);
    }
    if (nr)
        st.push(nr);
    while (!polo.empty())
    {
        int val = st.top();
        st.pop();
        st.top() = op(st.top(), polo.top(), val);
        polo.pop();
    }
    cout << st.top();
}