Cod sursa(job #3292788)

Utilizator cristia_razvanCristia Razvan cristia_razvan Data 9 aprilie 2025 12:47:53
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>
#include <iostream>
#include <stack>
#include <string>
#include <cctype> 
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();
    nr.pop();
    
    if (op == '+')
        nr.push(st + dr);
    else if (op == '-')
        nr.push(st - dr);
    else if (op == '*')
        nr.push(st * dr);
    else 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.empty() && ops.top() != '(') {
                calc(ops.top());
                ops.pop();
            }
            if(!ops.empty())
                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 if (isdigit(s[i])) {
            int ac = 0;
            while (i < s.size() && isdigit(s[i])) {
                ac = ac * 10 + (s[i] - '0');
                i++;
            }
            nr.push(ac);
            i--;
        }
    }

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

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

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