Cod sursa(job #2691697)

Utilizator tomaionutIDorando tomaionut Data 29 decembrie 2020 17:20:24
Problema Evaluarea unei expresii Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char a[100005];
int st[100005];
int main()
{
    int i,top=0,x;
    fin >> a;
    for (i=0; a[i];)
    {
        if (a[i]=='+') i++;
        else if (a[i]=='-') {st[++top]=-1; i++;}
        else if (a[i]=='*') {st[++top]=-2; i++;}
        else if (a[i]=='/') {st[++top]=-3; i++;}
        else if (a[i]=='(') {st[++top]=-4; i++;}
        else if (a[i]==')')
        {
            i++;
            x=0;
            while (st[top]!=-4)
            {
                x+=st[top];
                top--;
            }
            top--;
            if (top==0) st[++top]=x;
            else
            {
            if (st[top]==-1)
            {
                st[top]=-x;
            }
            else if (st[top]==-2)
            {
                top--;
                st[top]*=x;
            }
            else if (st[top]==-3)
            {
                top--;
                st[top]/=x;
            }
            else st[++top]=x;
            }
        }
        else if ('0'<=a[i] and a[i]<='9')
        {
            x=0;
            while ('0'<=a[i] and a[i]<='9')
            {
                x=x*10+(a[i]-'0');
                i++;
            }
            if (top==0) st[++top]=x;
            else
            {
            if (st[top]==-1)
            {
                st[top]=-x;
            }
            else if (st[top]==-2)
            {
                top--;
                st[top]*=x;
            }
            else if (st[top]==-3)
            {
                top--;
                st[top]/=x;
            }
            else st[++top]=x;
            }
        }
    }
    x=0;
    for (i=1; i<=top; i++)
        x+=st[i];
    fout << x;
    return 0;
}