Cod sursa(job #2851508)

Utilizator Madalin_IonutFocsa Ionut-Madalin Madalin_Ionut Data 18 februarie 2022 19:10:33
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.43 kb
#include <bits/stdc++.h>

using namespace std;

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

char s[100003];
stack<int> st;
int n;
const int pard = 2e9;
const int scadere = 2e9 - 1;
const int stea = 2e9 - 2;
const int impartire = 2e9 - 3;

void CalcParanteza()
{
    int x = 0;
    while (st.top() != pard)
    {
        if (st.top() == scadere)
        {
            x = -x;
            st.pop();
        }
        if (st.top() == stea)
        {
            st.pop();
            x = x * st.top();
        }
        else if (st.top() == impartire)
        {
            st.pop();
            x = st.top() / x;
        }
        else x += st.top();
        st.pop();
    }
    st.pop();
    if (!st.empty())
    {
        if (st.top() == scadere)
        {
            x = -x;
            st.pop();
        }
        if (st.top() == stea)
        {
            st.pop();
            x = x * st.top();
            st.pop();
            st.push(x);
        }
        else if (st.top() == impartire)
        {
            st.pop();
            x = st.top() / x;
            st.pop();
            st.push(x);
        }
        else st.push(x);
    }
    else st.push(x);
}

void Rezolvare()
{
    int i, x;
    n = strlen(s);
    st.push(pard);
    for (i = 0; i < n; i++)
        if ('0' <= s[i] && s[i] <= '9')
        {
            x = 0;
            while ('0' <= s[i] && s[i] <= '9')
            {
                x = x * 10 + s[i] - '0';
                i++;
            }
            i--;
            if (st.top() == scadere)
            {
                x = -x;
                st.pop();
            }
            if (st.top() == stea)
            {
                st.pop();
                x = x * st.top();
                st.pop();
                st.push(x);
            }
            else if (st.top() == impartire)
            {
                st.pop();
                x = st.top() / x;
                st.pop();
                st.push(x);
            }
            else st.push(x);
        }
        else if (s[i] == '(') st.push(pard);
        else if (s[i] == ')') CalcParanteza();
        else if (s[i] == '-') st.push(scadere);
        else if (s[i] == '*') st.push(stea);
        else if (s[i] == '/') st.push(impartire);
    CalcParanteza();
    fout << st.top() << "\n";
    fout.close();
}

int main()
{
    fin >> s;
    Rezolvare();
}