Cod sursa(job #2983897)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 23 februarie 2023 11:41:56
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <bits/stdc++.h>
#define MAXSZ 100005

using namespace std;

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

char expr[MAXSZ];

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

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

int main() {
    fin.getline(expr, MAXSZ);

    stack<int> operands;
    stack<char> operators;
    for (int i = 0; expr[i]; i++) {
        if (expr[i] >= '0' && expr[i] <= '9') {
            int nr = 0;
            while (expr[i] >= '0' && expr[i] <= '9')
                nr = nr * 10 + (expr[i++] - '0');
            i--;
            operands.push(nr);
            continue;
        }
        if (expr[i] == '(') {
            operators.push(expr[i]);
            continue;
        }
        if (expr[i] == ')') {
            while (operators.top() != '(') {
                int b = operands.top(); operands.pop();
                int a = operands.top(); operands.pop();
                char op = operators.top(); operators.pop();
                operands.push(evaluate(a, b, op));
            }
            operators.pop();
            continue;
        }
        while (!operators.empty() && getOperatorOrder(expr[i]) <= getOperatorOrder(operators.top())) {
            int b = operands.top(); operands.pop();
            int a = operands.top(); operands.pop();
            char op = operators.top(); operators.pop();
            operands.push(evaluate(a, b, op));
        }
        operators.push(expr[i]);
    }

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

    fout << operands.top();
    return 0;
}