Cod sursa(job #3269753)

Utilizator Tudor28Ceclan Tudor Tudor28 Data 20 ianuarie 2025 16:54:21
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>
#include <iostream>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

bool isOperation(char c)
{
    if (c == '+' || c == '-' || c == '*' || c == '/')
    {
        return true;
    }
    return false;
}
int priority(char c)
{
    if (c == '+' || c == '-')
    {
        return 1;
    }
    if (c == '*' || c == '/')
    {
        return 2;
    }
    return -1;
}
void procesOperation(stack<int> &s, char operatie)
{
    int r = s.top();
    s.pop();
    int l = s.top();
    s.pop();

    switch (operatie)
    {
    case '+':
        s.push(r + l);
        break;
    case '-':
        s.push(l - r);
        break;
    case '*':
        s.push(r * l);
        break;
    case '/':
        s.push(l / r);
        break;
    }
}
int evaluate(string s)
{
    stack<int> n;
    stack<char> op;
    int i = 0;
    while (s[i])
    {
        if (s[i] == '(')
        {
            op.push('(');
            i++;
        }
        else if (s[i] == ')')
        {
            while (op.top() != '(')
            {
                procesOperation(n, op.top());
                op.pop();
            }
            op.pop();
            i++;
        }
        else if (isOperation(s[i]))
        {

            while (!op.empty() && priority(op.top()) >= priority(s[i]))
            {
                procesOperation(n, op.top());
                op.pop();
            }
            op.push(s[i]);
            i++;
        }
        else
        {
            int nr = 0;
            while (isdigit(s[i]))
            {
                nr = nr * 10 + s[i++] - '0';
            }
            n.push(nr);
        }
    }
    while (!op.empty())
    {
        procesOperation(n, op.top());
        op.pop();
    }
    return n.top();
}
int main()
{
    string s;
    fin >> s;
    fout << evaluate(s);
    return 0;
}