Cod sursa(job #3375962)

Utilizator SergiuS3003Sergiu Stancu Nicolae SergiuS3003 Data 14 noiembrie 2026 16:41:59
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.5 kb
#include <fstream>
#include <stack>
#include <string>
#include <iostream>
using namespace std;

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

struct Node {
    char op;
    long long val;
    Node(char o, long long v) : op(o), val(v) {}
};
bool isDigit(char c) {
    return c >= '0' && c <= '9';
}
int eval(stack<Node> &st)
{
    stack<Node> aux;
    while(!st.empty() && st.top().op != '(')
    {
        Node node = st.top();
        st.pop();
        aux.push(node);
    }
    if(!st.empty())
    {
        st.pop();
    }
    int nrCrt = 0, semn = 1;
    while(!aux.empty())
    {
        Node node = aux.top();
        aux.pop();
        if(node.op == '+')
            semn = 1;
        else if(node.op == '-')
            semn = -1;
        else
            nrCrt += semn * node.val;
    }
    return nrCrt;
}
int main() {
    
    string s;
    fin >> s;
    stack<Node> st;

    for(int i = 0; i < s.size(); i++)
    {
        if(s[i] == '(')
        {
            st.push(Node('(', 0));
        }
        else if(isDigit(s[i]))
        {
            long long num = 0;
            while(i < s.size() && isDigit(s[i]))
            {
                num = num * 10 + (s[i] - '0');
                i++;
            }
            i--;
            if(!st.empty() && (st.top().op == '*' || st.top().op == '/'))
            {
                Node op = st.top();
                st.pop();

                Node operand1 = st.top();
                st.pop();
                if(op.op == '*')
                    num = operand1.val * num;
                else
                    num = operand1.val / num;
                st.push(Node(' ', num));
            }
            else 
            {
                st.push(Node(' ', num));
            }
        }
        else if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')
        {
            st.push(Node(s[i], 0));
        }
        else if(s[i] == ')')
        {
            int nrCrt = eval(st);
            if(!st.empty() && (st.top().op == '*' || st.top().op == '/'))
            {
                Node op = st.top();
                st.pop();
                Node operand1 = st.top();
                st.pop();
                if(op.op == '*')
                    nrCrt = operand1.val * nrCrt;
                else
                    nrCrt = operand1.val / nrCrt;
                st.push(Node(' ', nrCrt));
            }
            else 
            {
                st.push(Node(' ', nrCrt));
            }
        }
    }
    fout << eval(st) << "\n";

    return 0;
}