Cod sursa(job #3324725)

Utilizator Bogdan_ZZait Bogdan Bogdan_Z Data 23 noiembrie 2025 11:54:16
Problema Evaluarea unei expresii Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.84 kb
#include <iostream>
#include <fstream>
#include <stack>

using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
struct element
{
    int nr;
    char caracter;
};

inline int applyOperation(int a, char op, int b)
{
    switch (op)
    {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            return a / b;
        default:
            return -1;
    }
}

int parseNr(string &s, int &poz)
{
    int nr = 0;
    while (poz < s.size() && isdigit(s[poz]))
    {
        nr = nr * 10 + s[poz] - '0';
        poz++;
    }
    poz--;
    return nr;
}

int evaluare(stack<element> &S)
{
    bool evaluat = false;
    while (!evaluat)
    {
        int nrVf = S.top().nr;
        S.pop();
        if (S.empty())
        {
            return nrVf;
        }
        char operatie = S.top().caracter;
        S.pop();
        if (!S.empty())
        {
            int nr1 = S.top().nr;
            S.pop();
            int rez = applyOperation(nrVf, operatie, nr1);
            S.push({rez, ' '});
        }
        else
        {
            int rez = applyOperation(nrVf, operatie, 0);
            S.push({rez, ' '});
        }
    }
    return 0;
}

int main()
{
    string s;
    stack<element> S;
    f >> s;
    int semn = 1;
    for (int poz = 0; poz < s.size(); poz++)
    {
        if (isdigit(s[poz]))
        {
            int nr2 = parseNr(s, poz) * semn;
            semn = 1;
            if (!S.empty() && (S.top().caracter == '/' || S.top().caracter == '*'))
            {
                char op = S.top().caracter;
                S.pop();
                int nr1 = S.top().nr;
                S.pop();
                int rez = applyOperation(nr1, op, nr2);
                S.push({rez, ' '});
            }
            else
            {
                S.push({nr2, ' '});
            }
        }
        else if (s[poz] == ')')
        {
            ///evaluez expresia inapoi pana la prima paranteza deschisa (
            stack<element> S2;
            while (S.top().caracter != '(')
            {
                S2.push(S.top());
                S.pop();
            }
            S.pop(); /// scot si paranteza
            S.push({evaluare(S2), ' '});
        }
        else if (s[poz] != '-')
        {
            S.push({0, s[poz]});
        }
        else if (s[poz] == '-')
        {
            if (poz == 0 || s[poz - 1] == '(')
            {
                semn = -1;
            }
            else
            {
                S.push({0, s[poz]});
            }
        }
    }
    stack<element> S2;
    while (!S.empty())
    {
        S2.push(S.top());
        S.pop();
    }
    g << evaluare(S2);
    return 0;

}