Cod sursa(job #3291534)

Utilizator alexscanteieScanteie Alexandru alexscanteie Data 5 aprilie 2025 00:46:39
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <fstream>
#include <string>
#include <stack>
using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

int opr(char c) {
    if (c == '+' || c == '-')
        return 1;
    if (c == '*' || c == '/')
        return 2;
    if (c == '(')
        return -1;
    throw "Ce-ai facut prietene? Ai aruncat un operator necunoscut";
}

void calc(stack<int>& numere, stack<char>& operatori) {
    int b = numere.top();
    numere.pop();
    int a = numere.top();
    numere.pop();
    char op = operatori.top();
    operatori.pop();

    switch (op) {
        case '+':
            numere.push(a + b);
            break;
        case '-':
            numere.push(a - b);
            break;
        case '*':
            numere.push(a * b);
            break;
        case '/':
            if (b == 0)
                throw "Nu se poate prietene sa imparti la 0 ;)";
            numere.push(a / b);
            break;
        default:
            throw "Ai aruncat un operator necunoscut";
    }
}

int main() {
    string s;
    fin >> s;

    stack<int> numere;
    stack<char> operatori;
    
    for (int i = 0; i < s.size(); i++) {
        if (isdigit(s[i])) 
        {
            int n = 0;
            while (i < s.size() && isdigit(s[i])) {
                n = n * 10 + (s[i] - '0');
                ++i;
            }

            --i; // skip double increment
            numere.push(n);
        }
        else if (s[i] == '(') 
        {
            operatori.push('(');
        }
        else if (s[i] == ')') 
        {
            while (operatori.top() != '(')
                calc(numere, operatori);
            operatori.pop(); // pop (
        }
        else 
        {
            // calculate the expression
            while (!operatori.empty() && opr(operatori.top()) >= opr(s[i]))
                calc(numere, operatori);
            operatori.push(s[i]);
        }
    }

    while (!operatori.empty())
        calc(numere, operatori);

    fout << numere.top() << '\n';

    return 0;
}