Cod sursa(job #2828935)

Utilizator Toni1817Ungureanu Ionut Toni1817 Data 8 ianuarie 2022 10:08:08
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.74 kb
#include <iostream>
#include <stack>
#include <cstring>
#include <fstream>
using namespace std;

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

int prioritate(stack<char> C, int x)
{
    int y = C.top();
    if(x == '+' && y == '*' || x == '+' && y == '/')
        return 0;
    if(x == '-' && y == '*' || x == '-' && y == '/')
        return 0;
    if(x == '*' && y == '/' || x == '/' && y == '*')
        return 0;
    return 1;
}
void operatie(stack<int> &S, stack<char> &C)
{
    int rez;
    int x;
    x = S.top();
    S.pop();
    int y;
    y = S.top();
    S.pop();
    if(C.top() == '+')
    {
        rez = x + y;
        S.push(rez);
    }
    else if(C.top() == '-')
    {
        rez = y - x;
        S.push(rez);
    }
    else if(C.top() == '*')
    {
        rez = x * y;
        S.push(rez);
    }
    else if(C.top() == '/')
    {
        rez = y / x;
        S.push(rez);
    }
}

int main()
{
    ///(1+1)*13+10/2
    char a[100010];
    int aux = 0, p = 1;
    int b = 0, c[100010] = {0};
    stack<int> S;
    stack<char> C;
    cin >> a;
    int n = strlen(a);
    for(int i = 0; i < n; i++)
    {
        if(C.empty() && !isdigit(a[i]))
            C.push(a[i]);
        else if(isdigit(a[i]))
        {
            c[b++] = (a[i] - '0');
            if(!isdigit(a[i + 1]))
            {
                for(int j = 0; j < b; j++)
                {
                    aux = aux * 10 + c[j];
                    c[j] = 0;
                }
                S.push(aux);
                p = 1;
                b = 0;
                aux = 0;
            }
            /**int aux = 0;
            if(isdigit(a[i + 1]))
            {

                /**aux = aux * 10 + (a[i] - '0');
                aux = aux * 10 + (a[i + 1] - '0');
                i++;
            }
            else
                aux = (a[i] - '0');
            S.push(aux); */
        }
        else if(a[i] == ')')
        {
            if(C.top() == '(')
                C.pop();
            else
            {
                while(C.top() != '(')
                {
                    operatie(S, C);
                    C.pop();
                }
                C.pop();
            }
        }
        else if(prioritate(C, a[i]) == 1 && !isdigit(a[i]))
            C.push(a[i]);
        else if(a[i] == '(')
            C.push(a[i]);
        else
        {
            while(!C.empty() && prioritate(C, a[i]) == 0)
            {
                operatie(S, C);
                C.pop();
            }
            C.push(a[i]);
        }
    }
    while(!C.empty())
    {
        operatie(S, C);
        C.pop();
    }
    cout << S.top();

    return 0;
}