Cod sursa(job #2698897)

Utilizator CatalinPangaleanuCatalin Pangaleanu CatalinPangaleanu Data 23 ianuarie 2021 11:11:02
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <fstream>
#include <stack>

using namespace std;

ifstream cin("evaluare.in");
ofstream cout("evaluare.out");

stack<char> sign;
stack<int> num;

char s[100000], t[150000];

inline int Precedence(char ch)
{   if (ch=='*' || ch=='/')
        return 2;
    return 1;
}

int main()
{   int j, i, x, y;
    cin>>s;
    cin.close();
    j=-1;
    for (i=0;s[i];++i)
        if (isdigit(s[i]))
        {   while (isdigit(s[i]))
            {   t[++j]=s[i];
                ++i;
            }
            t[++j]=' ';
            --i;
        }
        else if (s[i]==')')
            {   while (sign.top()!='(')
                {   t[++j]=sign.top();
                    sign.pop();
                }
                sign.pop();
            }
            else
            {   while (!sign.empty() && sign.top()!='(' && Precedence(s[i])<=Precedence(sign.top()))
                {   t[++j]=sign.top();
                    sign.pop();
                }
                sign.push(s[i]);
            }
    while (!sign.empty())
    {   t[++j]=sign.top();
        sign.pop();
    }
    //cout<<t;
    for (i=0;t[i];++i)
        if (isdigit(t[i]))
        {   x=0;
            while (isdigit(t[i]))
            {   x=x*10+t[i]-'0';
                ++i;
            }
            num.push(x);
            --i;
        }
        else if (t[i]!=' ')
            {   x=num.top();
                num.pop();
                y=num.top();
                num.pop();
                if (t[i]=='*')
                    num.push(x*y);
                else if (t[i]=='/')
                        num.push(y/x);
                    else if (t[i]=='+')
                            num.push(x+y);
                        else
                            num.push(y-x);
            }
    cout<<num.top();
    cout.close();

    return 0;
}