Cod sursa(job #3344408)

Utilizator Gabriel_DaescuDaescu Gabriel Florin Gabriel_Daescu Data 1 martie 2026 22:43:01
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <fstream>
#include <stack>
#define NMAX 100002
using namespace std;
ifstream  fin("evaluare.in");
ofstream fout("evaluare.out");
char ch[NMAX];
stack<int> valori;
stack<char> operatori;

void efectuare_operatii()
{
    int a,b;
    char op;

    b=valori.top();
    valori.pop();
    a=valori.top();
    valori.pop();

    op=operatori.top();
    operatori.pop();

    if(op=='+')
    {
        valori.push(a+b);
    }

    if(op=='-')
    {
        valori.push(a-b);
    }

    if(op=='*')
    {
        valori.push(a*b);
    }

    if(op=='/')
    {
        valori.push(a/b);
    }
}

int prioritate(char op)
{
    if(op=='+' || op=='-')
    {
        return 1;
    }

    if(op=='*' || op=='/')
    {
        return 2;
    }

    if(op=='(')
    {
        return -1;
    }
}

int main()
{
    fin>>ch;

    for(int i=0; ch[i]; i++)
    {
        if(ch[i]>='0' && ch[i]<='9')
        {
            int val=0;
            while(ch[i]>='0' && ch[i]<='9')
            {
                val=val*10+(ch[i]-'0');
                i++;
            }
            i--;
            valori.push(val);
        }
        else
        {
            if(ch[i]=='(')
            {
                operatori.push('(');
            }
            else
            {
                if(ch[i]==')')
                {
                    while(!operatori.empty() && operatori.top()!='(')
                    {
                        efectuare_operatii();
                    }
                    operatori.pop();
                }
                else
                {
                    while(!operatori.empty() && prioritate(operatori.top())>=prioritate(ch[i]))
                    {
                        efectuare_operatii();
                    }
                    operatori.push(ch[i]);
                }
            }
        }
    }

    while(!operatori.empty())
    {
        efectuare_operatii();
    }

    fout<< valori.top() << "\n";

    return 0;
}