Cod sursa(job #1091459)

Utilizator kiralalaChitoraga Dumitru kiralala Data 25 ianuarie 2014 18:30:37
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.44 kb
#include <fstream>
#include <cstring>
#include <stack>
#define NMAX 100005

using namespace std;
//forma poloneza
FILE* f=freopen("evaluare.in","r",stdin);
FILE* o=freopen("evaluare.out","w",stdout);

char exp[NMAX];
char pol[NMAX*3];
int ind;
stack<char> op;
stack<long> num;

char sign[]="*/-+",l1[]="/*";

void ToPolish()
{
    int l=strlen(exp);
    for(int i=0;i<l;++i)
    {
        char c=exp[i];
        switch(c)
        {
            case'+':case'-':
                while(!op.empty()&&strchr(sign,op.top()))
                {
                    pol[ind++]=op.top();
                    pol[ind++]=' ';
                    op.pop();
                }
            op.push(c);
            break;
            case'*':case'/':
                while(!op.empty()&&strchr(l1,op.top()))
                {
                    pol[ind++]=op.top();
                    pol[ind++]=' ';
                    op.pop();
                }
            op.push(c);
            break;
            case'(':
                op.push(c);
            break;
            case')':
                while(op.top()!='(')
                {
                    pol[ind++]=op.top();
                    pol[ind++]=' ';
                    op.pop();
                }
                op.pop();
            break;
            default:
                while(i<l&&exp[i]>='0'&&exp[i]<='9')
                {
                    pol[ind++]=exp[i];
                    i+=1;
                }
                pol[ind++]=' ';
                i-=1;
            break;
        }
    }
    while(!op.empty()) {
        pol[ind]=op.top();
        pol[ind+1]=' ';
        ind+=2;
        op.pop();
    }
}

void Operation(char c)
{
    long b=num.top(); num.pop();
    long a=num.top(); num.pop();
    switch (c)
    {
        case '+': num.push(a+b); break;
        case '-': num.push(a-b); break;
        case '*': num.push(a*b); break;
        case '/': num.push(a/b); break;
    }
}

void Number(char c[])
{
    long x=0;
    for(int i=0;i<strlen(c);++i)
        x=x*10+(c[i]-'0');
    num.push(x);
}

void Evaluate()
{
    char *p=strtok(pol," ");
    while(p)
    {
        if(strstr(sign,p))
            Operation(p[0]);
        else
            Number(p);
        p=strtok(NULL," ");
    }
}

int main()
{
    scanf("%s",exp);
    ToPolish();
    Evaluate();
    printf("%ld",num.top());

    return 0;
}