Cod sursa(job #2263926)

Utilizator cyg_andrei_HHendoreanu Andrei Sebastian cyg_andrei_H Data 19 octombrie 2018 16:34:57
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <cstdio>
#include <cctype>

using namespace std;

const int NMAX=100000;
char op[(NMAX>>1)+5];
int polo[NMAX+5];
int pr(char ch)
{
    switch(ch)
    {
        case '+' : return 1;
        case '-' : return 1;
        case '*' : return 2;
        case '/' : return 2;
        case '(' : return 0;
        case ')' : return -1;
    }
}
int oper(int n,int m,char o)
{
    switch(o)
    {
        case '+' : return n+m;
        case '-' : return m-n;
        case '*' : return n*m;
        case '/' : return m/n;
    }
}
int main()
{
    freopen("evaluare.in","r",stdin);
    freopen("evaluare.out","w",stdout);
    int last,top,top2,t,t2;
    char ch;
    last=top=top2=0;
    while(scanf("%c",&ch)!=EOF&&ch!='\n'&&ch!=' ')
    {
        if(isdigit(ch))
        {
            if(last)
                polo[top2]=polo[top2]*10+(ch-48);
            else
            {
                polo[++top2]=ch-48;
                last=1;
            }
        }
        else
        {
            last=0;
            if(!top)
            {
                op[++top]=ch;
                continue;
            }
            t=pr(ch);
            t2=pr(op[top]);
            if(t==-1)
            {
                do
                {
                    --top2;
                    polo[top2]=oper(polo[top2+1],polo[top2],op[top--]);
                    t=pr(op[top]);
                }while(t);
                --top;
                continue;
            }
            if(t>t2)  
                op[++top]=ch;
            else
            {
               while(t2>=t)
               {
                   --top2;
                   polo[top2]=oper(polo[top2+1],polo[top2],op[top--]);
                   t2=pr(op[top]);
               }
                op[++top]=ch;
            }
        }
    }
    while(top)
    {
        --top2;
        polo[top2]=oper(polo[top2+1],polo[top2],op[top--]);
    }
    printf("%d\n",polo[1]);
    return 0;
}