Cod sursa(job #2291176)

Utilizator AndreiJJIordan Andrei AndreiJJ Data 27 noiembrie 2018 18:47:20
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <fstream>

using namespace std;
ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");
const int bracket = 2E9, times = 2E9 + 1, divide = 2E9 + 2, Minus = 2E9 + 3, Nmax = 1E5 + 2;
char a[Nmax];
int st[Nmax], top;
bool IsDigit (char ch)
{
    return ('0' <= ch && ch <='9');
}
int main()
{
    int i, x;
    fin >> a;
    for (i = 0; a[i];)
    {
        if (a[i] == '+')
            i++;
        else if (a[i] == '*')
        {
            st[++top] = times;
            i++;
        }
        else if (a[i] == '/')
        {
            st[++top] = divide;
            i++;
        }
        else if (a[i] == '-')
        {
            st[++top] = Minus;
            i++;
        }
        else if (a[i] == '(')
        {
            st[++top] = bracket;
            i++;
        }
        else if (IsDigit(a[i]))
        {
            x = 0;
            while (IsDigit(a[i]))
            {
                x = x * 10 + (a[i] - '0');
                i++;
            }
            if (!top)
                st[++top] = x;
            else if (st[top] == Minus)
                st[top] = -x;
            else if (st[top] == times)
            {
                top--;
                st[top] *= x;
            }
            else if (st[top] == divide)
            {
                top--;
                st[top] /= x;
            }
            else st[++top] = x;
        }
        else /// a[i] = ')'
        {
            i++;
            x = 0;
            while (st[top] != bracket)
            {
                x += st[top];
                top--;
            }
            top--;
            if (!top)
                st[++top] = x;
            else if (st[top] == Minus)
                st[top] = -x;
            else if (st[top] == times)
            {
                top--;
                st[top] *= x;
            }
            else if (st[top] == divide)
            {
                top--;
                st[top] /= x;
            }
            else st[++top] = x;
        }
    }
    int ans = 0;
    for (i = 1; i <= top; i++)
        ans += st[i];
    fout << ans << "\n";
    fout.close();
    return 0;
}