Cod sursa(job #2710131)

Utilizator George_CristianGeorge Dan-Cristian George_Cristian Data 21 februarie 2021 21:35:09
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <fstream>
#include <cstring>
#include <stack>

using namespace std;

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

char sir[100005];
int nrl, poz;
stack<char> operatori;
stack<int> operanzi;

bool precedenta(char op1, char op2) {
    if (op1 == '(')
        return true;
    if ((op1 == '+' || op1 == '-') && (op2 == '*' || op2 == '/'))
        return true;
    return false;
}

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;
    }
}

void evaluare_expresie() {
    int b = operanzi.top();
    operanzi.pop();
    int a = operanzi.top();
    operanzi.pop();
    operanzi.push(eval(a, b, operatori.top()));
    operatori.pop();
}

int numar() {
    int nr = 0;
    while (isdigit(sir[poz]))
        nr = nr * 10 + sir[poz++] - '0';
    return nr;
}

void evaluare() {
    while (poz < nrl) {
        switch (sir[poz]) {
            case '(': {
                operatori.push('(');
                poz++;
                break;
            }
            case ')': {
                while (operatori.top() != '(')
                    evaluare_expresie();
                operatori.pop();
                poz++;
                break;
            }
            case '+':
            case '-':
            case '*':
            case '/': {
                while (!operatori.empty() && !precedenta(operatori.top(), sir[poz]))
                    evaluare_expresie();
                operatori.push(sir[poz++]);
                break;
            }
            default:
                operanzi.push(numar());
        }
    }
    while (!operatori.empty())
        evaluare_expresie();
}

int main() {
    f.getline(sir, 100005);
    nrl = strlen(sir);
    evaluare();
    g << operanzi.top();
    return 0;
}