Cod sursa(job #2869218)

Utilizator cdenisCovei Denis cdenis Data 11 martie 2022 13:17:33
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

const int MAX=1e5+5;
int n;
char exp[MAX];

int eval(int st, int dr)
{
    int i=st,j,k=0,stk[MAX],nr,nrp,rez=0,aux;
    char op[MAX];
    op[0]=0;
    while(i<=dr)
    {
        if(exp[i]=='-')
        {
            stk[++k]=0;
            op[k]='-';
            i++;
        }
        else if(exp[i]=='(')
        {
            j=i,nrp=1;
            while(nrp)
            {
                j++;
                if(exp[j]=='(')
                    nrp++;
                else if(exp[j]==')')
                    nrp--;
            }
            stk[++k]=eval(i+1,(j++)-1);
            if(strchr("+-*/",exp[j]))
                op[k]=exp[j];
            i=j+1;
        }
        else if(isdigit(exp[i]))
        {
            nr=0;
            while(isdigit(exp[i]))
                nr=nr*10+exp[i++]-'0';
            stk[++k]=nr;
            if(i<=dr)
                op[k]=exp[i++];
        }
    }
    while(k)
    {
        if(op[k-1]=='+' || op[k-1]==0)
            rez+=stk[k--];
        else if(op[k-1]=='-')
            rez-=stk[k--];
        else
        {
            int kk=k-1;
            while(kk && strchr("*/",op[kk]))
                kk--;
            kk++;
            j=kk;
            aux=stk[j];
            while(j<k)
            {
                if(op[j]=='*')
                    aux*=stk[j+1];
                else
                    aux/=stk[j+1];
                j++;
            }
            k=kk;
            stk[k]=aux;
        }
    }
    return rez;
}

int main()
{
    fin >> exp;
    fout << eval(0,strlen(exp)-1);
    return 0;
}