Cod sursa(job #2697617)

Utilizator CatalinPangaleanuCatalin Pangaleanu CatalinPangaleanu Data 19 ianuarie 2021 09:30:18
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

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

string s;

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

inline void InfixToPostfix()
{   int j, i;
    stack<char> st;
    j=-1;
    for (i=0;s[i];++i)
        if (isdigit(s[i]))
        {   while (isdigit(s[i]))
            {   ++j;
                s[j]=s[i];
                ++i;
            }
            --i;
        }
        else if (s[i]=='(')
                st.push('(');
            else if (s[i]==')')
                {   while (st.top()!='(')
                    {   s[++j]=st.top();
                        st.pop();
                    }
                    st.pop();
                }
                else
                {   while (!st.empty() && st.top()!='(' && Precedence(s[i])<=Precedence(st.top()))
                    {   s[++j]=st.top();
                        st.pop();
                    }
                    st.push(s[i]);
                }
    while (!st.empty())
    {   s[++j]=st.top();
        st.pop();
    }
}

inline int Power(int b, int e)
{   int ans;
    ans=1;
    while (e)
    {   if (e%2)
            ans=ans*b;
        b=b*b;
        e/=2;
    }
    return ans;
}

inline int Calc(int a, int b, char op)
{   if (op=='^')
        return Power(a, b);
    if (op=='*')
        return a*b;
    if (op=='/')
        return a/b;
    if (op=='+')
        return a+b;
    return a-b;
}

inline int Evaluate()
{   int i, x;
    vector<int> st;
    for (i=0;s[i];++i)
        if (isdigit(s[i]))
        {   x=0;
            while (isdigit(s[i]))
            {   x=x*10+s[i]-'0';
                ++i;
            }
            st.push_back(x);
            --i;
        }
        else if (s[i]!='(' && s[i]!=')')
            while (st.size()>=2)
            {   x=Calc(st[st.size()-1], st[st.size()-2], s[i]);
                st.pop_back(), st.pop_back();
                st.push_back(x);
            }
    return st.back();
}

int main()
{   ios_base::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    cin>>s;
    cin.close();
    InfixToPostfix();
    cout<<Evaluate();
    cout.close();

    return 0;
}