Cod sursa(job #3346636)

Utilizator dargrigaDarius Griga dargriga Data 14 martie 2026 18:07:10
Problema Evaluarea unei expresii Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.17 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
string s;
stack<char> op;
stack <int> nr;
int i=0;
int calc()
{
    int r=nr.top();
    nr.pop();
    while(!op.empty()&&!nr.empty())
    {
        if(op.top()=='(')
        {
            op.pop();
            break;
        }
        char oper=op.top();
        if(oper=='*')
            r*=nr.top();
        else if(oper=='/')
            r=nr.top()/r;
        else if(oper=='+')
            r+=nr.top();
        else if(oper=='-')
            r=nr.top()-r;
        nr.pop();
        op.pop();
    }
    return r;
}
int getnr()
{
    int r=0;
    while(s[i]>='0'&&s[i]<='9')
        r*=10, r+=s[i]-'0', i++;
    i--;
    return r;
}
void afis(stack<char> a, stack<int> b)
{
    while(!a.empty())
        cout << a.top() << " ", a.pop();
    cout << '\n';
    while(!b.empty())
        cout << b.top() << " ", b.pop();
    cout << "\n-------------------\n";
}

int main()
{
    f >> s;
    bool negativ=false;
    while(i<s.size())
    {
        if(s[0]=='-'&&!nr.empty()&&negativ==false)
        {
            int save=nr.top();
            nr.pop();
            nr.push(save*-1);
            negativ=true;
        }
        if(s[i]>='0'&&s[i]<='9')
            nr.push(getnr());
        else
        {
            if(!nr.empty()&&((i>=1&&s[i]=='-'&&(s[i-1]<'0'||s[i-1]>'9'))||(s[i]=='-'&&i==0)))
            {
                int save=nr.top();
                nr.pop();
                nr.push(save*-1);
            }
            if(s[i]==')')
                nr.push(calc());
            else if(s[i]=='('||op.empty())
                op.push(s[i]);
            else if(op.top()=='*'||op.top()=='/')
            {
                nr.push(calc());
                op.push(s[i]);
            }
            else if((op.top()=='+'||op.top()=='-')&&(s[i]=='+'||s[i]=='-'))
            {
                nr.push(calc());
                op.push(s[i]);
            }
            else
                op.push(s[i]);
        }
        afis(op, nr);
        i++;
    }
    nr.push(calc());
    g << nr.top();
    return 0;
}