Cod sursa(job #3346638)

Utilizator dargrigaDarius Griga dargriga Data 14 martie 2026 18:15:22
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("evaluare.in");
ofstream g("evaluare.out");

string s;
stack<int> nr;
stack<char> op;
int i=0;

int inainte(char c) {
    if(c=='+' || c=='-')
        return 1;
    if(c=='*' || c=='/')
        return 2;
    return 0;
}

int calc() {
    int b = nr.top();
    nr.pop();
    int a = nr.top();
    nr.pop();
    char c = op.top();
    op.pop();
    if(c=='+')
        return a+b;
    if(c=='-')
        return a-b;
    if(c=='*')
        return a*b;
    return a/b;
}

int getnr() {
    int r=0;
    while(i<s.size()&&isdigit(s[i]))
        r = r*10 + (s[i]-'0'), i++;
    i--;
    return r;
}

int main() {
    f >> s;

    for(i=0; i<s.size(); i++) {

        if(isdigit(s[i]))
        {
            nr.push(getnr());
        }
        else if(s[i]=='(')
        {
            op.push('(');
        }
        else if(s[i]==')')
        {
            while(!op.empty()&&op.top()!='(')
                nr.push(calc());
            op.pop();
        }
        else
        {
            if(s[i]=='-'&&(i==0||s[i-1]=='('))
                nr.push(0);
            while(!op.empty()&&inainte(op.top())>=inainte(s[i]))
                nr.push(calc());
            op.push(s[i]);
        }
    }
    while(!op.empty())
        nr.push(calc());
    g << nr.top();
    return 0;
}