Cod sursa(job #2855032)

Utilizator Kawaiimeatball13Russu Mihaela Kawaiimeatball13 Data 21 februarie 2022 23:54:41
Problema Evaluarea unei expresii Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.73 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;

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

char s[100001];
int l;
stack <int> operanzi;
stack <char> operatori;

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

int se_poate(char c1, char c2)
{
    if(prioritate(c2) < prioritate(c1))
        return 1;
    return 0;
}

int in_numar(char *s, int &i)
{
    int nr = 0;
    for(; s[i] >= '0' && s[i] <= '9'; ++i)
    {
        //cout << i << ' ';
        nr = nr * 10 + (s[i] - '0');
    }

    return nr;
}

int calcul(int x, int y, char c)
{
    if(c == '+')
        return x + y;
    if(c == '-')
        return x - y;
    if(c == '*')
        return x * y;
    if(c == '/')
        return x / y;
}

int evaluare(char *s, int l)
{
    for(int i = 0; i < l; ++i)
    {
        if(strchr("/*+-", s[i]) && operatori.empty())
            operatori.push(s[i]);
        else if(s[i] >= '0' && s[i] <= '9')
        {
            int nr = in_numar(s, i);
            operanzi.push(nr);
            i--;
        }
        else if(s[i] == ')')
        {
            while(operatori.top() != '(')
            {
                int y = operanzi.top();
                operanzi.pop();
                int x = operanzi.top();
                operanzi.pop();
                int rez = calcul(x, y, operatori.top());
                operatori.pop();
                operanzi.push(rez);
            }
            operatori.pop();
        }
        else if(s[i] == '(')
            operatori.push(s[i]);
        else if(strchr("/*+-", s[i]))
        {
            if(se_poate(s[i], operatori.top()))
                operatori.push(s[i]);
            else
            {
                while(!operatori.empty() && !se_poate(s[i], operatori.top()))
                {
                    int y = operanzi.top();
                    operanzi.pop();
                    int x = operanzi.top();
                    operanzi.pop();
                    int rez = calcul(x, y, operatori.top());
                    operatori.pop();
                    operanzi.push(rez);
                }
                operatori.push(s[i]);
            }
        }
    }
    while(!operatori.empty())
    {
        int y = operanzi.top();
        operanzi.pop();
        int x = operanzi.top();
        operanzi.pop();
        int rez = calcul(x, y, operatori.top());
        operatori.pop();
        operanzi.push(rez);
    }

    return operanzi.top();
}

int main()
{
    fin.getline(s, 256);
    l = strlen(s);
    fout << evaluare(s, l);
    return 0;
}