Cod sursa(job #3293372)

Utilizator petru-robuRobu Petru petru-robu Data 11 aprilie 2025 16:13:56
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.3 kb
#include <bits/stdc++.h>
using namespace std;

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

unordered_map<char, int> precedence = {
    {'+', 1},
    {'-', 1},
    {'*', 2},
    {'/', 2},
    {'(', -1},
    {')', -1}
};

int calc(int val1, int val2, int op)
{
    if(op == '+')
        return val1 + val2;

    else if(op == '-')
        return val1 - val2;

    else if(op == '*')
        return val1 * val2;
    
    else if(op == '/')
        return val1 / val2;

    return -1;
}

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

void doOperation(stack<int> &numStack, stack<char>& opStack)
{
    if(numStack.size() < 2 || opStack.size() < 1)
    {
        cout<<"Cannot do operation";
        return;
    }
        
    int val1 = numStack.top();
    numStack.pop();

    int val2 = numStack.top();
    numStack.pop();

    char op = opStack.top();
    opStack.pop();

    int new_val = calc(val2, val1, op);
    numStack.push(new_val);
}

int main()
{
    string s;
    fin>>s;
    
    stack<int> numStack;
    stack<char> opStack;

    for(int i=0; i<s.size(); i++)
    {
        cout<<"Curr element: ";
        if(isdigit(s[i]))
        {
            int val = 0;
            while(i < s.size() && isdigit(s[i]))
            {
                val = val*10 + (s[i] - '0');
                i++;
            }
            i --;

            cout<<val<<' ';
            numStack.push(val);
        }
        else if(s[i] == '(')
        {
            cout<<s[i]<<' ';
            opStack.push(s[i]);
        }
        else if(s[i] == ')')
        {
            cout<<s[i]<<' ';
            while(!opStack.empty() && opStack.top() != '(')
            {
                doOperation(numStack, opStack);
            }
            
            //pop the '('
            if(!opStack.empty())
                opStack.pop();
        }

        else if(isOperator(s[i]))
        {
            cout<<s[i]<<' ';
            while(!opStack.empty() && precedence[s[i]] <= precedence[opStack.top()])
            {
                doOperation(numStack, opStack);
            }

            opStack.push(s[i]);
        }
        cout<<"\n";
    }

    while(!opStack.empty())
        doOperation(numStack, opStack);
    
    if(!numStack.empty())
       fout<<numStack.top()<<'\n';
    
    return 0;
}