Cod sursa(job #3203084)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 13 februarie 2024 09:10:34
Problema Evaluarea unei expresii Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <bits/stdc++.h>
#define MAXSZ 100000

using namespace std;

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

string expr;

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

int eval(int a, int b, char op) {
    switch (op) {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            return a / b;
        default:
            return 0;
    }
}

int eval(string& expr) {
    stack<int> operands;
    stack<char> operators;

    for (int i = 0; i < expr.size(); i++) {
        if (expr[i] >= '0' && expr[i] <= '9') {
            int num = 0;
            while (i < expr.size() && expr[i] >= '0' && expr[i] < '9')
                num = num * 10 + (int) (expr[i++] - '0');
            i--;
            operands.push(num);
        } else {
            switch (expr[i]) {
                case '(':
                    operators.push(expr[i]);
                    break;
                case ')':
                    while (operators.top() != '(') {
                        int b = operands.top(); operands.pop();
                        int a = operands.top(); operands.pop();
                        char op = operators.top(); operators.pop();

                        operands.push(eval(a, b, op));
                    }
                    operators.pop();
                    break;
                default:
                    while (!operators.empty() && getOrder(operators.top()) >= getOrder(expr[i])) {
                        int b = operands.top(); operands.pop();
                        int a = operands.top(); operands.pop();
                        char op = operators.top(); operators.pop();

                        operands.push(eval(a, b, op));
                    }
                    operators.push(expr[i]);
                    break;
            }
        }
    }

    while (!operators.empty()) {
        int b = operands.top(); operands.pop();
        int a = operands.top(); operands.pop();
        char op = operators.top(); operators.pop();

        operands.push(eval(a, b, op));
    }

    return operands.top();
}

int main() {
    getline(fin, expr);
    fout << eval(expr);
    return 0;
}