Cod sursa(job #2875929)

Utilizator lucriLuchian Cristian lucri Data 22 martie 2022 17:59:52
Problema Evaluarea unei expresii Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.57 kb
#include <bits/stdc++.h>
std::ifstream cin("evaluare.in");
std::ofstream cout("evaluare.out");
std::stack <int> x,p;
char a[100010];
int b[100010],e[100010],nrp,l;
int cn(int &poz)
{
    int ans=0;
    while('0'<=a[poz]&&a[poz]<='9')
    {
        ans*=10;
        ans+=a[poz++]-'0';
    }
    --poz;
    return ans;
}
void rezolva(int &i)
{
    for(;i<l;++i)
    {
        if(a[i]=='(')
        {
            b[++nrp]=i;
            p.push(nrp);
            ++i;
            rezolva(i);
        }
        else if(a[i]==')')
        {
            int pa=p.top();
            p.pop();
            e[i]=pa;
            for(int j=i-1;j>b[pa];--j)
            {
                if(a[j]==')')
                    j=b[e[j]];
                if(a[j]=='-')
                {
                    int z=x.top();
                    x.pop();
                    int q=x.top();
                    x.pop();
                    x.push(q-z);
                }
                else if(a[j]=='+')
                {
                    int z=x.top();
                    x.pop();
                    int q=x.top();
                    x.pop();
                    x.push(q+z);
                }
            }
            return;
        }
        else if(a[i]=='*'||a[i]=='/')
        {
            int z=x.top();
            x.pop();
            bool ceva=false;
            if(a[i]=='*')
                ceva=true;
            ++i;
            if(a[i]=='(')
            {
                b[++nrp]=i;
                p.push(nrp);
                ++i;
                rezolva(i);
            }
            else
                x.push(cn(i));
            int q=x.top();
            x.pop();
            if(ceva==true)
                x.push(z*q);
            else
                x.push(z/q);
        }
        else if(a[i]!='+'&&a[i]!='-')
            x.push(cn(i));
    }
    return;
}
int main()
{
    cin>>a;
    l=strlen(a);
    int z=0;
    rezolva(z);
    for(int i=l-1;i>=0;--i)
    {
        if(a[i]==')')
            i=b[e[i]];
        else if(a[i]=='+'||a[i]=='-')
        {
            if(a[i]=='-')
            {
                int z=x.top();
                x.pop();
                int q=x.top();
                x.pop();
                x.push(q-z);
            }
            else if(a[i]=='+')
            {
                int z=x.top();
                x.pop();
                int q=x.top();
                x.pop();
                x.push(q+z);
            }
        }
    }
    cout<<x.top();
    return 0;
}