Cod sursa(job #2962097)

Utilizator RobertlelRobert Robertlel Data 7 ianuarie 2023 19:02:31
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.36 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <cstring>


using namespace std;

ifstream f("evaluare.in");
ofstream g("evaluare.out");

int i , n;

char exp[100005];

stack < char > op;

stack <int > num;

int calculate (int val1 , int val2 , char oper)
{
    if (oper == '+')
        return val1 + val2;
    if (oper == '-')
        return val1 - val2;
    if (oper == '*')
        return val1 * val2;
    if (oper == '/')
        return val1 / val2;
}

int priority (char  a)
{
    if (a == '+' || a == '-')
        return 1;
    if (a == '*' || a == '/')
        return 2;
        return 0;
}

int main()
{
    f >> exp;
    int n = strlen (exp) - 1;
    for (int i = 0 ; i <= n ; i++)
    {
        if (exp[i] == '(')
                op.push ('(');
        else
        if (isdigit (exp[i]))
        {
            int val = 0;
            while (isdigit (exp[i]) && i <= n)
            {
                val = val * 10 + (exp[i] - '0');
                i++;
            }
            num.push (val);
            i--;
        }
        else
        if (exp[i] == ')')
        {
            while (op.top () != '(' && op.empty() == 0)
            {
                char operat = op.top ();
                op.pop ();
                int num2 = num.top ();
                num.pop ();
                int num1 = num.top();
                num.pop ();
                num.push (calculate (num1 , num2 , operat));
            }
            if (op.empty () == 0)
                op.pop ();
        }
        else
            {
                while (op.empty () == 0 && priority (op.top ()) >= priority (exp[i]))
                {
                    char operat = op.top ();
                    op.pop ();
                    int num2 = num.top ();
                    num.pop ();
                    int num1 = num.top ();
                    num.pop ();
                    num.push (calculate (num1 , num2 , operat));
                }
                op.push (exp[i]);
            }
    }

    while (op.empty () == 0)
    {
        char operat = op.top ();
        op.pop ();
        int num2 = num.top ();
        num.pop ();
        int num1 = num.top ();
        num.pop ();
        num.push (calculate (num1 , num2 , operat));
    }
    g << num.top ();
    return 0;
}