Cod sursa(job #3346614)

Utilizator dargrigaDarius Griga dargriga Data 14 martie 2026 16:34:34
Problema Evaluarea unei expresii Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 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;
    while(i<s.size())
    {
        if(s[i]>='0'&&s[i]<='9')
            nr.push(getnr());
        else
        {
            if(!op.empty()&&(s[i]=='+'||s[i]=='-')&&(op.top()=='*'||op.top()=='/'))
            {
                nr.push(calc());
                i--;
            }
            else if(s[i]==')')
                nr.push(calc());
            else
            {
                op.push(s[i]);
            }
        }
        //afis(op, nr);
        i++;
    }
    nr.push(calc());
    g << nr.top();
    return 0;
}