Cod sursa(job #2789113)

Utilizator stefandutastefandutahoria stefanduta Data 26 octombrie 2021 21:41:24
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.81 kb
#include <fstream>
#include <cstring>
#define NMAX 100005
using namespace std;
ifstream in ("evaluare.in");
ofstream out ("evaluare.out");

int factori[NMAX], nrfactori, nroperatori;
char operatori[NMAX];
char s[NMAX];
int i;

bool isdigit (char x)
{
    return x >= '0' && x <='9';
}

int factor ()
{
    int nr = 0;
    while (isdigit(s[i]))
    {
        nr = nr * 10 + s[i] - '0';
        ++i;
    }
    return nr;
}

void pushfactor (int x)
{
    factori[nrfactori] = x;
    ++nrfactori;
}

void pushoperator (char x)
{
    if (x == '+' || x == '-' || x == '*' || x == '/' || x == '(' || x == ')')
    {
        operatori[nroperatori] = x;
        ++nroperatori;
    }
}

int poplastfactor ()
{
    if (nrfactori > 0)
    {
        nrfactori--;
        return factori[nrfactori];
    }
    return 0;
}

char poplastoperator ()
{
    if (nroperatori > 0)
    {
        nroperatori--;
        return operatori[nroperatori];
    }
    return '\0';
}

char lastoperator ()
{
    if(nroperatori)
        return operatori[nroperatori - 1];
    return '\0';
}

int main()
{
    in.getline(s, NMAX);
    int n, nr;
    char op;
    n = strlen(s);

    i = 0;
    pushoperator('+');
    while (i < n)
    {
        while(s[i] == '(')
        {
            pushoperator('(');
            pushoperator('+');
            ++i;
        }

        op = lastoperator();
        if (op == '*')
        {
            pushfactor(poplastfactor() * factor());
            poplastoperator();
        }
        else if (op == '/')
        {
            pushfactor(poplastfactor() / factor());
            poplastoperator();
        }
        else if (op == '+' || op == '-')
        {
            pushfactor(factor());
        }

        while (s[i] == ')')
        {
            nr = 0;
            op = poplastoperator();
            while (op != '(')
            {
                if (op == '+')
                    nr = nr + poplastfactor();
                else if (op == '-')
                    nr = nr - poplastfactor();
                op = poplastoperator();
            }
            if (lastoperator() == '*')
            {
                nr = poplastfactor() * nr;
                poplastoperator();
            }
            else if (lastoperator() == '/')
            {
                nr = poplastfactor() / nr;
                poplastoperator();
            }
            pushfactor(nr);
            ++i;
        }

        pushoperator(s[i++]);
    }

    //out << nrfactori << " " << nroperatori << '\n';
    int suma = 0;
    while (nrfactori > 0)
    {
        if (poplastoperator() == '+')
            suma = suma + poplastfactor();
        else
            suma = suma - poplastfactor();
    }

    out << suma;
    return 0;
}