Cod sursa(job #2795715)

Utilizator MattiaMattia Iojica Mattia Data 6 noiembrie 2021 20:23:27
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.57 kb
#include <bits/stdc++.h>
#define mod 9973
#define ull unsigned long long

using namespace std;

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

int ordine(char op)
{
    if(op == '+' || op == '-')
        return 1;
    if(op == '*' || op == '/')
        return 2;

    return 0;
}

int calcul(int val1, int val2, char op)
{
    switch(op)
    {
        case '+': return val1 + val2;
        case '-': return val1 - val2;
        case '*': return val1 * val2;
        case '/': return val1 / val2;
    }

}


int solve(string s)
{
    stack <int> valori;
    stack <char> operatie;

    for(int i = 0; i < s.length(); i++)
    {

        if(s[i] == ' ')
            continue;
        else
            if(s[i] == '(')
                operatie.push(s[i]);
        else
            if(isdigit(s[i]))
            {
                int val = 0;
                while(i < s.length() && isdigit(s[i]))
                {
                    val = val * 10 + (s[i] - '0');
                    i++;
                }

                valori.push(val);
                i--;
            }
        else
            if(s[i] == ')')
            {
                while(!operatie.empty() && operatie.top() != '(')
                {
                    int val2 = valori.top();
                    valori.pop();

                    int val1 = valori.top();
                    valori.pop();

                    char op = operatie.top();
                    operatie.pop();

                    valori.push(calcul(val1, val2, op));
                }

                if(!operatie.empty())
                    operatie.pop();
            }

        else
            {
                while(!operatie.empty() && ordine(operatie.top())
                      >= ordine(s[i]))
                {
                    int val2 = valori.top();
                    valori.pop();

                    int val1 = valori.top();
                    valori.pop();

                    char op = operatie.top();
                    operatie.pop();

                    valori.push(calcul(val1, val2, op));
                }
                operatie.push(s[i]);
            }
    }

    while(!operatie.empty())
    {
        int val2 = valori.top();
        valori.pop();

        int val1 = valori.top();
        valori.pop();

        char op = operatie.top();
        operatie.pop();

        valori.push(calcul(val1, val2, op));
    }


    return valori.top();
}

int main()
{
    string s;

    f >> s;

    g << solve(s);
}