Cod sursa(job #3225241)

Utilizator Razvan23Razvan Mosanu Razvan23 Data 17 aprilie 2024 10:37:18
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.44 kb
#include <bits/stdc++.h>
#define pd 2000000000
#define Minus 2000000003
#define stea 2000000001
#define slash 2000000002

using namespace std;

int st[100005], top;
char a[100005];

int main()
{
    int i, x;
    ifstream fin("evaluare.in");
    ofstream fout("evaluare.out");
    fin >> a;
    top = 0;
    for (i = 0; a[i]; )
    {
        if (a[i] == '+') i++;
        else if (a[i] == '-')
            {st[++top] = Minus; i++;}
        else if (a[i] == '(')
        {
            st[++top] = pd;
            i++;
        }
        else if ('0' <= a[i] && a[i] <= '9')
        {
            x = 0;
            while ('0' <= a[i] && a[i] <= '9')
            {
                x = x * 10 + a[i] - '0';
                i++;
            }
            /// verific daca inainte pe stiva este
            /// * sau /
            if (top == 0)
                st[++top] = x;
            else
            {
                if (st[top] == Minus)
                {
                    st[top] = -x;
                }
                else if (st[top] == stea)
                {
                    top--;
                    st[top] *= x;
                }
                else if (st[top] == slash)
                {
                    top--;
                    st[top] /= x;
                }
                else st[++top] = x;
            }
        }
        else if (a[i] == '*')
        {
            st[++top] = stea;
            i++;
        }
        else if (a[i] == '/')
        {
            st[++top] = slash;
            i++;
        }
        else /// a[i] == ')'
        {
            i++;
            x = 0;
            while (st[top] != pd)
            {
                x += st[top];
                top--;
            }
            top--;
            if (top == 0)st[++top] = x;
            else
            {
                if (st[top] == Minus)
                {
                    st[top] = -x;
                }
                else if (st[top] == stea)
                {
                    top--;
                    st[top] *= x;
                }
                else if (st[top] == slash)
                {
                    top--;
                    st[top] /= x;
                }
                else st[++top] = x;
            }
        }
    }
    x = 0;
    for (i = 1; i <= top; i++)
        x += st[i];
    fout << x << "\n";
    fout.close();
    return 0;
}