Cod sursa(job #2756277)

Utilizator dey44andIoja Andrei-Iosif dey44and Data 30 mai 2021 16:37:10
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.67 kb
#include <bits/stdc++.h>

#define input "evaluare.in"
#define output "evaluare.out"

using namespace std;

ifstream in(input);
ofstream out(output);

string expresie, polish;
stack < int > stiva, stiva_eval;

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

bool isoperator(int c)
{
    if(c == '+' || c == '-' || c == '*' || c == '/')
        return true;
    return false;
}

void Read_Compute()
{
    in >> expresie;
    unsigned L = expresie.size(), i = 0;
    while(i < L)
    {
        if(isdigit(expresie[i]))
        {
            while(isdigit(expresie[i]))
            {
                polish.push_back(expresie[i]);
                i++;
            }
            polish.push_back(' ');
        }
        else if(expresie[i] == '(')
        {
            stiva.push(expresie[i]);
            i++;
        }
        else if(expresie[i] == ')')
        {
            while(!stiva.empty() && stiva.top() != '(')
            {
                polish.push_back(stiva.top());
                polish.push_back(' ');
                stiva.pop();
            }
            if(!stiva.empty()) stiva.pop();
            i++;
        }
        else
        {
            while(!stiva.empty() && priority_eval(stiva.top()) >= priority_eval(expresie[i]))
            {
                polish.push_back(stiva.top());
                polish.push_back(' ');
                stiva.pop();
            }
            stiva.push(expresie[i]);
            i++;
        }
    }
    while(!stiva.empty())
    {
        polish.push_back(stiva.top());
        polish.push_back(' ');
        stiva.pop();
    }
}

int calculator(int a, int b, int op)
{
    if(op == '+')
        return a + b;
    if(op == '*')
        return a * b;
    if(op == '-')
        return a - b;
    if(op == '/')
        return a / b;
    return 0;
}

void Evaluate()
{
    unsigned L = polish.size(), i = 0;
    while(i < L)
    {
        if(isdigit(polish[i]))
        {
            int x = 0;
            while(isdigit(polish[i]))
            {
                x = x * 10 + polish[i] - '0';
                i++;
            }
            stiva_eval.push(x);
        }
        else if(isoperator(polish[i]))
        {
            int b = stiva_eval.top(); stiva_eval.pop();
            int a = stiva_eval.top(); stiva_eval.pop();
            int c = calculator(a, b, polish[i]);
            stiva_eval.push(c);
            i++;
        }
        else i++;
    }
    out << stiva_eval.top();
}

int main()
{
    Read_Compute();
    Evaluate();
    return 0;
}