Cod sursa(job #3212449)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 11 martie 2024 19:06:55
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define dbg(x) cout << #x << ": " << x << "\n";
#define sz(x) ((int)x.size())

using ll = long long;

const string fn = "evaluare";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");

string s;
stack<char> ops;
stack<int> nr;

bool isop(char x)
{
    return strchr("+-*/", x);
}
int pri(char x)
{

    if (x == '+' || x == '-')
        return 1;
    if (x == '*' || x == '/')
        return 2;
    return -1;
}

void comp(char op)
{
    int R = nr.top();
    nr.pop();
    int L = nr.top();
    nr.pop();
    if (op == '+')
        nr.push(L + R);
    if (op == '-')
        nr.push(L - R);
    if (op == '*')
        nr.push(L * R);
    if (op == '/')
        nr.push(L / R);
}

int main()
{

    fin >> s;
    for (int i = 0; i < sz(s); ++i)
    {

        if (s[i] == ' ')
            continue;
        if (s[i] == '(')
            ops.push('(');
        else if (s[i] == ')')
        {
            while (ops.top() != '(')
                comp(ops.top()), ops.pop();
            ops.pop();
        }
        else if (isop(s[i]))
        {
            while (!ops.empty() && pri(ops.top()) >= pri(s[i]))
                comp(ops.top()), ops.pop();
            ops.push(s[i]);
        }
        else
        {
            int nrac = 0;
            while (isdigit(s[i]))
                nrac = nrac * 10 + s[i++] - '0';
            nr.push(nrac);
            --i;
        }
    }
    while (!ops.empty())
    {
        comp(ops.top());
        ops.pop();
    }
    fout << nr.top();

    return 0;
}