Cod sursa(job #2979014)

Utilizator 100pCiornei Stefan 100p Data 14 februarie 2023 18:35:06
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
#include <bits/stdc++.h>

#define MAX 1000

using namespace std;

string str;

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

stack <int> numbers[MAX + 5];
stack <char>signs[MAX + 5];

int depth;

int ordin(char c)
{
    if(c == '*' || c == '/')
        return 2;

    return 1;
}

int make_operation(int a, int b, char oper)
{
    if(oper == '*')
        return a * b;
    if(oper == '/')
        return a / b;
    if(oper == '+')
        return a + b;
    return a - b;
}

int main()
{
    fin >> str;
    str += ')';
    for(int i = 0; i < str.size(); ++i)
    {
        if(str[i] == '(')
            depth++;
        else
        {
            if(str[i] >= '0' && str[i] <= '9')
            {
                int nr = 0;
                while(i < str.size() && str[i] >= '0' && str[i] <= '9')
                    nr = nr * 10 + str[i++] - '0';
                i--;
                numbers[depth].push(nr);
            }

            if(strchr("+-/*", str[i]))
            {
                while(!signs[depth].empty() && ordin(signs[depth].top()) >= ordin(str[i]))
                {
                    int a = numbers[depth].top();
                    numbers[depth].pop();
                    int b = numbers[depth].top();
                    numbers[depth].pop();

                    char oper = signs[depth].top();
                    signs[depth].pop();

                    int rez = make_operation(b, a, oper);
                    numbers[depth].push(rez);
                }
                signs[depth].push(str[i]);
            }

            if(str[i] == ')')
            {
                while(!signs[depth].empty())
                {
                    int a = numbers[depth].top();
                    numbers[depth].pop();
                    int b = numbers[depth].top();
                    numbers[depth].pop();

                    char oper = signs[depth].top();
                    signs[depth].pop();

                    int rez = make_operation(b, a, oper);
                    numbers[depth].push(rez);
                }
                if(depth)
                {
                    numbers[depth - 1].push(numbers[depth].top());
                    depth--;
                }
            }
        }
    }
    fout << numbers[0].top();
}