Cod sursa(job #1331343)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 31 ianuarie 2015 15:48:35
Problema Evaluarea unei expresii Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <cstdio>
#include <stack>
#include <cstring>
#include <cctype>

#define Nmax 100000 + 10

using namespace std;

int i , j , n , p1 , s1 , nr;

int prior[200];

char s[Nmax] , semn[Nmax] , post[Nmax];

stack < int > Stack;

int operatie(int a , int b , char c)
{
    if (c == '+') return a + b;
    if (c == '-') return a - b;
    if (c == '*') return a * b;
    if (c == '/') return a / b;
}

int main()
{
    freopen("evaluare.in","r",stdin);
    freopen("evaluare.out","w",stdout);

    s[0] = '('; gets(s+1); n = strlen(s); s[n] = ')';

    prior[')'] = 1;
    prior['+'] = prior['-'] = 2;
    prior['*'] = prior['/'] = 3;
    prior['/'] = 4;

    for (i = 1; i <= n; ++i)
    {
        if (s[i] == '(')
            semn[++s1] = '(';
        else
        {
            if ( isdigit ( s[i] ) )
            {
                while ( isdigit ( s[i] ) )
                    post[++p1] = s[i++];

                post[++p1] = ','; --i;
            }
            else
            {
                for (j = s1; j && semn[j] != '(' && prior[semn[j]] >= prior[s[i]]; --j)
                    post[++p1] = semn[j];

                if (s[i] != ')') semn[s1 = j + 1] = s[i];
                else s1 = j - 1;
            }
        }
    }

    for (i = 1; i <= p1; ++i)
    {
        if ( isdigit ( post[i] ) )
        {
            nr = 0;

            while ( isdigit ( post[i] ) )
                nr = nr * 10 + post[i++] - '0';

            Stack.push(nr);
        }
        else
        {
            nr = Stack.top();
            Stack.pop();

            Stack.top() = operatie( Stack.top() , nr , post[i]);
        }
    }

    printf("%d\n", Stack.top());

    return 0;
}