Cod sursa(job #1779598)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 15 octombrie 2016 14:30:25
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.67 kb
#include <iostream>
#include <fstream>
#include <string.h>
#include <stack>
#define NMAX 100001

using namespace std;

ifstream in("evaluare.in");
ofstream out("evaluare.out");
char expr[NMAX];
char postfix[NMAX];
stack<long long int> eval;

int priority(char op)
{
    if(op == '*' || op == '/')
        return 2;
    if(op == '+' || op == '-')
        return 1;
    return 0;
}

void transf()
{
    unsigned int length = strlen(expr);
    unsigned int lengthp = -1;
    for (unsigned int i = 0; i < length; i++)
    {
        if (strchr("0123456789", expr[i]))
        {
            while(i < length && strchr("0123456789", expr[i]))
            {
                postfix[ ++lengthp ] = expr[i];
                i++;
            }
            postfix[ ++ lengthp ] = '!';
        }
        if(expr[i] == '(')
            eval.push(expr[i]);
        if(expr[i] == ')')
        {
            while(eval.top() != '(')
            {
                postfix[ ++lengthp ] = eval.top();
                eval.pop();
            }
            eval.pop();
        }
        if(strchr("+-/*", expr[i]))
        {
            if(eval.empty())
                eval.push(expr[i]);
            else
            {
                while(!eval.empty() && priority(eval.top()) >= priority(expr[i]))
                {
                    postfix[ ++ lengthp ] = eval.top();
                    eval.pop();
                }
                eval.push(expr[i]);
            }
        }
    }
    while(!eval.empty())
    {
        postfix[ ++ lengthp ] = eval.top();
        eval.pop();
    }
    postfix[ ++ lengthp ] = '\0';
}

int main()
{
    in.getline(expr, NMAX);
    in.close();
    transf();
    unsigned int length = strlen(postfix);
    long long int x = 0;
    for(unsigned int i = 0; i < length; i++)
    {
        if (strchr("0123456789", postfix[i]))
        {
            x = 0;
            while(postfix[i] != '!')
            {
                x = x * 1LL * 10 + (long long)(postfix[i] - '0');
                i++;
            }
            eval.push(x);
        }
        if (strchr("+-/*", postfix[i]))
        {
            long long int x, y;
            x = eval.top();
            eval.pop();
            y = eval.top();
            eval.pop();
            if (postfix[i] == '+')
                eval.push(y + x);
            else if (postfix[i] == '-')
                eval.push(y - x);
            else if (postfix[i] == '*')
                eval.push(y * x);
            else if (postfix[i] == '/')
                eval.push(y / x);
        }
    }
    out << eval.top() << "\n";
    out.close();
    return 0;
}