Cod sursa(job #2564164)

Utilizator NotTheBatmanBruce Wayne NotTheBatman Data 1 martie 2020 18:40:59
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <fstream>
#include <iostream>
#include <string>
#define bracket 1e9 + 1
#define times 1e9 + 2
#define divide 1e9 + 3
#define Minus 1e9 + 4


using namespace std;

const int N = 100005;

string a;
int st[N], top;

void Read ()
{
    ifstream fin ("evaluare.in");
    fin >> a;
    fin.close();
}

void Solve ()
{
    int i;
    for (i = 0; a[i];)
    {
        if (a[i] == '+')
            i++;
        else if (a[i] == '(')
        {
            st[++top] = bracket;
            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 ('0' <= a[i] && a[i] <= '9')
        {
            int x = 0;
            while ('0' <= a[i] && a[i] <= '9')
            {
                x = x * 10 + a[i] - '0';
                i++;
            }
            if (st[top] == times)
                st[--top] *= x;
            else if (st[top] == divide)
                st[--top] /= x;
            else if (st[top] == Minus)
                st[top] = -x;
            else st[++top] = x;
        }
        else
        {
            i++;
            int x = 0;
            while (st[top] != bracket)
            {
                x += st[top];
                top--;
            }
            top--;
            if (st[top] == times)
                st[--top] *= x;
            else if (st[top] == divide)
                st[--top] /= x;
            else if (st[top] == Minus)
                st[top] = -x;
            else st[++top] = x;
        }
    }
    int ans = 0;
    for (int i = 1;  i <= top; i++)
        ans += st[i];
    ofstream fout ("evaluare.out");
    fout << ans << "\n";
    fout.close();
}

int main()
{
    Read();
    Solve();
    return 0;
}