Cod sursa(job #3292781)

Utilizator cristia_razvanCristia Razvan cristia_razvan Data 9 aprilie 2025 12:43:12
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

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

string s;
stack<char> ops;

stack<int> nr;

bool isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; }

int pri(char c) {
    if (c == '+' || c == '-') return 1;
    if (c == '*' || c == '/') return 2;
    return -1;
}

void calc(char op) {
    int dr = nr.top();
    nr.pop();
    int st = nr.top();
    if (op == '+') nr.push(st + dr);
    if (op == '-')
        ;
    nr.push(st - dr);
    if (op == '*') nr.push(st * dr);
    if (op == '/') nr.push(st / dr);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    fin >> s;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == ' ') continue;
        if (s[i] == '(')
            ops.push('(');
        else if (s[i] == ')') {
            while (ops.top() != '(') {
                calc(ops.top()), ops.pop();
            }
            ops.pop();
        } else if (isOperator(s[i])) {
            while (!ops.empty() && pri(ops.top()) >= pri(s[i])) {
                calc(ops.top()), ops.pop();
            }
            ops.push(s[i]);
        } else {
            int ac = 0;
            while (isdigit(s[i])) ac = ac * 10 + s[i++] - '0';
            i--;
        }
    }

    while (!ops.empty()) {
        calc(ops.top());
        ops.pop();
    }

    fout << nr.top() << "\n";

    fin.close();
    fout.close();
    return 0;
}