Cod sursa(job #2876072)

Utilizator T_george_TGeorge Teodorescu T_george_T Data 22 martie 2022 22:01:35
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <iostream>
#include <stack>
#include <fstream>
#include <cstring>
using namespace std;

const int mod = 1e9;

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

stack<int> numbers;
stack<char> operators;

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

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

void apply(){
    int val1 = numbers.top();
    numbers.pop();
    int val2=numbers.top();
    numbers.pop();
    numbers.push(op(val2, val1, operators.top()) % mod);
    operators.pop();
}

int evaluate(char s[]) {
    int l=strlen(s);
    for (int i = 0; i < l; i++) {
        if (s[i] >= '0' && s[i] <= '9') {
            int n = 0, j;
            for (j = i; s[j] <= '9' && s[j] >= '0'; j++)
                n = n * 10 + s[j] - '0';
            i = j - 1;
            numbers.push(n);
        }
        else if (s[i] == '(')
            operators.push('(');
        else if (s[i] == ')') {
            while (operators.top() != '(') {
                apply();
            }
            operators.pop();
        } else {
            while (!operators.empty() && precedence(operators.top()) >= precedence(s[i])) {
                apply();
            }
            operators.push(s[i]);
        }
    }
    while (!operators.empty()) {
        apply();
    }
    return numbers.top();
}

int main() {
    char expr[100001];
    in.getline(expr, 100001);
    out<<evaluate(expr);
    return 0;
}