Cod sursa(job #3154421)

Utilizator 1gbr1Gabara 1gbr1 Data 4 octombrie 2023 17:35:48
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

const int bracket = 1e9 + 1, divide = 1e9 + 2, times = 1e9 + 3, Minus = 1e9 + 4;

int st[100001], top;
string a;

int main()
{
    ifstream fin("evaluare.in");
    fin >> a;
    for (int i = 0; i < a.size(); i++)
    {
        if (a[i] == '+')
            continue;
        else if (a[i] == '-')
            st[++top] = Minus;
        else if (a[i] == '*')
            st[++top] = times;
        else if (a[i] == '/')
            st[++top] = divide;
        else if (a[i] == '(')
            st[++top] = bracket;
        else
        {
            int x = 0;
            if (isdigit(a[i])) {
                while (isdigit(a[i]))
                    x = x * 10 + (a[i++] - '0');
                i--;
            }
            else // a[i] == ')'
            {
                while (st[top] != bracket)
                    x += st[top--];
                top--;
            }
            if (!top)
                st[++top] = x;
            else if (st[top] == Minus)
                st[top] = -x;
            else if (st[top] == times)
            {
                st[top - 1] *= x;
                top--;
            }
            else if (st[top] == divide)
            {
                st[top - 1] /= x;
                top--;
            }
            else st[++top] = x;
        }
    }
    int ans = 0;
    for (int i = 1; i <= top; i++)
        ans += st[i];
    ofstream fout("evaluare.out");
    fout << ans << "\n";
}