Cod sursa(job #2723519)

Utilizator davidbejenariu2David Bejenariu davidbejenariu2 Data 14 martie 2021 14:18:39
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <stack>
#define N 100005

using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

void polska(char *exp, char *fp)
{
    stack <char> ops;
    int k = 0;

    for (int i = 0; exp[i]; ++i)
    {
        if (isdigit(exp[i]))
        {
            while (isdigit(exp[i]))
                fp[k++] = exp[i++];

            --i;
            fp[k++] = ',';
        }
        else
            if (strchr("*/(", exp[i]))
                ops.push(exp[i]);
            else
                if (strchr("+-", exp[i]))
                {
                    while (!ops.empty() && strchr("*/", ops.top()))
                    {
                        fp[k++] = ops.top();
                        ops.pop();
                    }

                    ops.push(exp[i]);
                }
                else
                {
                    while (!ops.empty() && ops.top() != '(')
                    {
                        fp[k++] = ops.top();
                        ops.pop();
                    }

                    ops.pop();
                }
    }

    while (!ops.empty())
    {
        fp[k++] = ops.top();
        ops.pop();
    }

    fp[k] = 0;
}

int main()
{
    char exp[N];
    char fp[N];

    fin >> exp;
    fin.close();

    polska(exp, fp);

    stack <int> ops;

    for (int i = 0; fp[i]; ++i)
    {
        if (isdigit(fp[i]))
        {
            int num = 0;

            while (isdigit(fp[i]))
                num = num * 10 + fp[i++] - '0';

            --i;
            ops.push(num);
        }
        else
            if (fp[i] != ',')
            {
                int a = ops.top(); ops.pop();
                int b = ops.top(); ops.pop();

                if (fp[i] == '+') ops.push(a + b);
                if (fp[i] == '-') ops.push(a - b);
                if (fp[i] == '*') ops.push(a * b);
                if (fp[i] == '/') ops.push(b / a);
            }
    }

    fout << ops.top();
    fout.close();

    return 0;
}