Cod sursa(job #3349674)

Utilizator BaraianTudorBaraian Tudor Stefan BaraianTudor Data 1 aprilie 2026 15:18:46
Problema Evaluarea unei expresii Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <iostream>
#include <queue>
#include <fstream>
#include <cstring>
#include <stack>
#define N_MAX 1000005
#define MOD 666013
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
string polish;
queue<int> nb;
stack<int> s;
int get_ord(char c) {
    if (c == '(')return 0;
    if (c == '+' || c == '-')return 1;
    return 2;
}
int perform_op(int a, int b, char op) {
    if (op == '+')return a + b;
    if (op == '-')return a - b;
    if (op == '*')return a * b;
    if (op == '/')return a / b;
}
void clean_paranthesis() {
    while (s.top() != '(') {
        polish.push_back(s.top());
        s.pop();
    }
    s.pop();
}
void process_operator(char op) {
    while (!s.empty() && get_ord(s.top()) >= get_ord(op)) {
        char c = s.top();
        polish.push_back(c);
        s.pop();
    }
    s.push(op);
}
void infix_to_polish() {
    char c;
    int nr = 0;
    while (in >> c) {
        if (isdigit(c)) {
            nr = nr * 10 + (c - '0');
        }
        else {
            if (nr > 0) {
                polish.push_back('1');
                nb.push(nr);
                nr = 0;
            }
            switch (c)
            {
            case '(':
                s.push(c);
                break;
            case ')':
                clean_paranthesis();
                break;
            default:
                process_operator(c);
            }
        }
    }
    if (nr > 0) {
        polish.push_back('1');
        nb.push(nr);
        nr = 0;
    }
    while (!s.empty()) {
        polish.push_back(s.top());
        s.pop();
    }
}
int main()
{
    infix_to_polish();
    stack<int> st;
    
    for (char c : polish) {
        if (c == '1') {
            st.push(nb.front());
            nb.pop();
        }
        else {
            int nr2 = st.top();
            st.pop();
            int nr1 = st.top();
            st.pop();
            st.push(perform_op(nr1, nr2, c));
        }
    }
    out << st.top();
    return 0;
}