Cod sursa(job #2845131)

Utilizator Irina.comanIrina Coman Irina.coman Data 7 februarie 2022 15:52:57
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.45 kb
#include <iostream>
#include <fstream>
#include <cctype>
#include <queue>
#include <cstring>
using namespace std;

queue<char> q;
queue<int> st;
char rez[300005];

bool hashigherprecedence(char x, char y)
{
    if (x == '*' or x == '/')
        return true;
    else if (x == '+' or x == '-' or x == '(')
    {
        if (y == '+' or y == '-' or y == '(')
            return true;
        else return false;
    }
}
bool isopeningpar(char x)
{
    if (x == '(')
        return true;
    else return false;
}
int operatie(char a, int x, int y)
{
    if (a == '+')
        return x + y;
    else if (a == '-')
        return x - y;
    else if (a == '*')
        return x * y;
    else if (a == '/')
        return x / y;
}

int main()
{
    ifstream fin("evaluare.in");
    ofstream fout("evaluare.out");
    char c[100005];
    int cnt = -1, rezfinal = 0;
    fin >> c;
    for (int i = 0; i < strlen(c); i++)
    {
        if (c[i] >= '0' and c[i] <= '9')
            rez[++cnt] = c[i];
        else if (c[i] == '+' or c[i] == '-' or c[i] == '*' or c[i] == '/')
        {
            rez[++cnt] = ',';
            while (!q.empty() and isopeningpar(q.front()) == false and hashigherprecedence(q.front(), c[i]) == false)
            {
                rez[++cnt] = q.front();
                q.pop();
            }
            q.push(c[i]);
        }
        else if (c[i] == '(')
            q.push(c[i]);
        else if (c[i] == ')')
        {
            while (!q.empty() and isopeningpar(q.front()) == false)
            {
                rez[++cnt] = q.front();
                q.pop();
            }
            q.pop();
        }
    }
    while (!q.empty())
    {
        rez[++cnt] = q.front();
        q.pop();
    }
    for (int i = 0; i < strlen(rez); i++)
    {
        if (isdigit(rez[i]))
        {
            int operand = 0;
            while(i < strlen(rez) and isdigit(rez[i]))
            {
                operand = operand * 10 + (rez[i] - '0');
                i++;
            }
            i--;
            st.push(operand);
        }
        else if (rez[i] == '+' or rez[i] == '-' or rez[i] == '*' or rez[i] == '/')
        {
            int op2 = st.front();
            st.pop();
            int op1 = st.front();
            st.pop();
            rezfinal = operatie(rez[i], op1, op2);
            st.push(rezfinal);
        }
    }
    fout << st.front();
    return 0;
}