Cod sursa(job #2340231)

Utilizator armigheGheorghe Liviu Armand armighe Data 10 februarie 2019 09:41:18
Problema Evaluarea unei expresii Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.49 kb
#include<fstream>
#include<cstring>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char s[100002],n;

int calc(int i)
{
    int x=0,p=1,sol=0,ii,k;
    if(s[i]=='(')
    {
        x=calc(i+1);
        k=1;
        i++;
        while(!(s[i]==')'&&k==1))
        {
            if(s[i]=='(')
                k++;
            else
            if(s[i]==')')
                k--;
            i++;
        }
        i++;
    }
    else
    {
        while(s[i]>='0'&&s[i]<='9')
        {
            x*=10;
            x+=s[i]-48;
            i++;
        }
    }
    p*=x;
    while(i<=n&&s[i]!=')')
    {
        while(s[i]=='*'||s[i]=='/')
        {
            x=0;
            ii=i;
            i++;
            if(s[i]=='(')
            {
                x=calc(i+1);
                k=1;
                i++;
                while(!(s[i]==')'&&k==1))
                {
                    if(s[i]=='(')
                        k++;
                    else
                    if(s[i]==')')
                        k--;
                    i++;
                }
                i++;
            }
            else
            {
                while(s[i]>='0'&&s[i]<='9'&&i<=n)
                {
                    x*=10;
                    x+=s[i]-48;
                    i++;
                }
            }
            if(s[ii]=='*')
                p*=x;
            else
                p/=x;
        }
        sol+=p;
        p=0;
        if(i<=n&&s[i]!=')')
        {
            if(s[i]=='+')
                p=1;
            else
                p=-1;
            i++;
            x=0;
            if(s[i]=='(')
            {
                x=calc(i+1);
                k=1;
                i++;
                while(!(s[i]==')'&&k==1))
                {
                    if(s[i]=='(')
                        k++;
                    else
                    if(s[i]==')')
                        k--;
                    i++;
                }
                i++;
            }
            else
            {
                while(s[i]>='0'&&s[i]<='9'&&i<=n)
                {
                    x*=10;
                    x+=s[i]-48;
                    i++;
                }
            }
            p*=x;
        }
    }
    sol+=p;
    return sol;
}

int main()
{
    int sol;
    f.getline(s+1,100001);
    n=strlen(s+1);
    sol=calc(1);
    g<<sol;
    return 0;
}