Cod sursa(job #2851491)

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

using namespace std;

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

char s[100003];
stack<int> st;
int n;

void Inmultire(int x)
{
    x = x * st.top();
    st.pop();
    st.push(x);
}

void Impartire(int x)
{
    x = st.top() / x;
    st.pop();
    st.push(x);
}

void CalcParanteza()
{
    int x = 0;
    while (st.top() != 2e9)
    {
        x += st.top();
        st.pop();
    }
    st.pop();
    st.push(x);
}

void Rezolvare()
{
    int i, x;
    int tip_op = 1;
    n = strlen(s);
    st.push(2e9);
    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 (tip_op == 1) st.push(x);
            else if (tip_op == 0) st.push(-x);
            else if (tip_op == 2) Inmultire(x);
            else if (tip_op == 3) Impartire(x);
        }
        else if (s[i] == '(') st.push(2e9);
        else if (s[i] == ')') CalcParanteza();
        else if (s[i] == '+') tip_op = 1;
        else if (s[i] == '-') tip_op = 0;
        else if (s[i] == '*') tip_op = 2;
        else tip_op = 3;
    CalcParanteza();
    fout << st.top() << "\n";
    fout.close();
}

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