Cod sursa(job #3004041)

Utilizator not_anduAndu Scheusan not_andu Data 16 martie 2023 09:06:34
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <fstream>
#include <cstring>
#include <stack>
#include <unordered_map>

using namespace std;

ifstream cin("evaluare.in");
ofstream cout("evaluare.out");

char s[100005];
stack<char> operatori;
stack<int> numere;
unordered_map<char, int> m;
int i, n;

int solve(int x, int y, char o)
{
    switch (o)
    {
    case '+':
        return x + y;
    case '-':
        return y - x;
    case '*':
        return x * y;
    case '/':
        return y / x;
    }
    return -3243;
}

bool cifra(char x)
{
    if (x >= '0' && x <= '9')
        return 1;
    else
        return 0;
}

void prioritati()
{
    m['+'] = 1;
    m['-'] = 1;
    m['*'] = 2;
    m['/'] = 2;
}

int formare()
{
    int nou = 0;
    while (cifra(s[i]) && i < n)
    {
        nou = nou * 10 + (s[i] - '0');
        i++;
    }
    i--;
    return nou;
}

void nebunie()
{
    int x = numere.top();
    numere.pop();
    int y = numere.top();
    numere.pop();
    char o = operatori.top();
    operatori.pop();
    numere.push(solve(x, y, o));
}

int main()
{
    prioritati();
    cin >> s;
    n = strlen(s);
    for (i = 0; i < n; i++)
    {
        if (cifra(s[i]))
        {
            int nou = formare();
            numere.push(nou);
        }
        else if (s[i] == '(')
            operatori.push('(');
        else if (s[i] == ')')
        {
            while (operatori.top() != '(' && !operatori.empty())
                nebunie();
            if (operatori.empty() == 0)
                operatori.pop();
        }
        else
        {
            while (!operatori.empty() && m[operatori.top()] >= m[s[i]])
                nebunie();
            operatori.push(s[i]);
        }
    }
    while (!operatori.empty())
        nebunie();
    cout << numere.top();
    return 0;
}