Cod sursa(job #3184161)

Utilizator MegaCoderMinoiu Teodor Mihai MegaCoder Data 14 decembrie 2023 17:13:20
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.39 kb
#include<fstream>
#include<string>
#include<stack>
std::ifstream fin("evaluare.in");//
std::ofstream fout("evaluare.out");
std::stack<char>operators;
std::stack<int>nrs;
std::string exp;
long long size;
int eval(int a, int b, char s)
{
    if(s=='+')
        return a+b;
    if(s=='-')
        return a-b;
    if(s=='*')
        return a*b;
    return a/b;
}


bool isGood(char op, char current)
{
    if(op=='(')
        return true;
    if((op=='+' || op=='-') && (current=='*' || current=='/'))
        return true;
    return false;
}
bool isOp(char local)
{
    return (local=='-' || local=='+' || local=='*' || local=='/' || local=='(' || local==')');
}


int createNum(int &index)
{
    int ans=0;
    while(!isOp(exp[index]) && index<size)
    {
        ans=ans*10;
        ans+=exp[index]-'0';
        ++index;
    }
    return ans;
}



void solve()
{
    for(int index=0; index<size; ++index)
    {
        if(exp[index]=='(')
            operators.push(exp[index]);

        else if(exp[index]==')')
        {
            while(operators.top()!='(')
            {
                int v1=nrs.top();
                nrs.pop();
                int v2=nrs.top();
                nrs.pop();
                char sign=operators.top();
                operators.pop();
                nrs.push(eval(v2, v1, sign));
            }
            operators.pop();
        }
        else if(isOp(exp[index]))
        {
            if(operators.empty() || isGood(operators.top(), exp[index]))
                operators.push(exp[index]);
            else
            {
                do
                {
                    int a=nrs.top();
                    nrs.pop();
                    int b=nrs.top();
                    nrs.pop();
                    char sign=operators.top();
                    operators.pop();
                    nrs.push(eval(b, a, sign));
                }while(!operators.empty() && !isGood(operators.top(), exp[index]));
                operators.push(exp[index]);
            }
        }
        else
        {
            nrs.push(createNum(index));
            --index;
        }
    }
    while(!operators.empty())
    {
        int a=nrs.top();
        nrs.pop();
        int b=nrs.top();
        nrs.pop();
        char sign=operators.top();
        operators.pop();
        nrs.push(eval(b, a, sign));
    }
    fout<<nrs.top();
}
int main()
{
    fin>>exp;
    size=exp.size();
    solve();
    return 0;
}