Cod sursa(job #2157271)

Utilizator TudoseSanzianaTudose Sanziana TudoseSanziana Data 9 martie 2018 14:25:08
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
using namespace std;

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

const int ASCII_MAX = 47;

char ch, last;
int priority[ASCII_MAX + 2];

stack<char> op;
stack<int> polo;

void evaluare()
{
    int num = polo.top();
    char semn = op.top();
    op.pop(); polo.pop();

    switch(semn)
    {
    case '+':
        polo.top() += num;
        break;
    case '-':
        polo.top() -= num;
        break;
    case '*':
        polo.top() *= num;
        break;
    case '/':
        polo.top() /= num;
    }
}

int main()
{
    priority['+'] = priority['-'] = 1;
    priority['*'] = priority['/'] = 2;
    priority['('] = 0;

    int nr;
    last = nr = 0;
    while(in >> ch)
    {
        if(isdigit(last) && !isdigit(ch))
        {
            polo.push(nr);
            nr = 0;
        }

        if(isdigit(ch))
            nr = nr * 10 + ch - '0';
        else if(ch == ')')
        {
            while(!op.empty() && op.top() != '(')
                    evaluare();
            op.pop();
        }
        else
        {
            if(ch == '(')
            {
                op.push('(');
                continue;
            }

            while(!op.empty() && priority[ch] <= priority[op.top()])
                evaluare();
            op.push(ch);
        }

        last = ch;
    }

    if(nr)
        polo.push(nr);

    while(!op.empty())
        evaluare();

    out << polo.top() << '\n';

    return 0;
}