Cod sursa(job #2133296)

Utilizator sulzandreiandrei sulzandrei Data 16 februarie 2018 19:11:12
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.52 kb
#include <fstream>
#include <vector>
#include <string>
#include <stack>
#include <cctype>
#include <sstream>
#define pb push_back
using namespace std;
std::ifstream in("evaluare.in");
std::ofstream out("evaluare.out");
struct op{
    int nr;
    bool oper;

    op(int n, bool b):nr(n),oper(b){}
};
vector<op> postFix;
int result = 0;
bool isOperator(char c){ return !isdigit(c)  && c !=')' && c!='(';}
int evaluateExpr(int a,char op, int b)
{
    switch(op)
    {
        case '+': return a+b;
        case '-': return a-b;
        case '*': return a*b;
        case '/': return a/b;

    }
}
void shutingYard(string I) // infix -> RPN
{
    int pre[255]; pre['+'] = 10;    pre['-'] = 10;    pre['*'] = 11;    pre['/'] = 11; pre['('] = -1;pre[')'] = -2;
    stack<char> operators;
    int i = 0;
    char token;
    while(i< I.size())
    {
        token = I[i];
        if(isdigit(token))
        {
            string nr("");
            nr+=token;
            while( i+1 < I.size() && isdigit(I[i+1]))
            {
                i++;
                token = I[i];
                nr+=I[i];
            }
            stringstream ss(nr);
            ss >> result;
            postFix.pb(op(result,false));
        }
        if(isOperator(token))
        {
            while ( operators.size()>0 && isOperator(operators.top())&&  pre[operators.top()]>=pre[(unsigned int)token])
            {
                 postFix.pb(op(operators.top(),true)), operators.pop();
            }

           operators.push(token);
        }
        if(token =='(')
           operators.push(token);
        if(token == ')')
        {
            while(operators.top() != '(')
            {
                postFix.pb(op(operators.top(),true)), operators.pop();
            }
            operators.pop();
        }
        i++;
    }
    while(!operators.empty())
    {
       postFix.pb(op(operators.top(),true)), operators.pop();
    }
}
void evalRPlr()
{
    stack<int> stac;
    int operand1,operand2;
    for(int i = 0 ; i < postFix.size(); i++)
        if(postFix[i].oper)
        {
            operand2 = stac.top(); stac.pop();
            operand1 = stac.top(); stac.pop();
            result = evaluateExpr(operand1, postFix[i].nr,operand2);
            stac.push(result);
        }
        else
            stac.push(postFix[i].nr);
    result = stac.top(); stac.pop();
}
int main()
{
    string s;
    in >> s;
    shutingYard(s);
    evalRPlr();
    out<<result;
    return 0;
}