Cod sursa(job #1570137)

Utilizator delia_99Delia Draghici delia_99 Data 16 ianuarie 2016 11:07:34
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <cstdio>
#include <cstring>
#include <stack>
#define NMAX 100000
using namespace std;
char s[NMAX+10],post[2*NMAX+10],semn[NMAX+10];
int i,n,ord[50],crt,crtp,val;
stack <int> rez;

void init()
{
    ord[')']=1;
    ord['+']=2;
    ord['-']=2;
    ord['*']=3;
    ord['/']=3;
    ord['(']=4;
}

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

int main()
{
    freopen("evaluare.in","r",stdin);
    freopen("evaluare.out","w",stdout);
    gets(s);
    n=strlen(s);
    s[n]=')';
    semn[++crt]='(';
    init();
    while(i<=n)
    {
        if(s[i]<'0' || s[i]>'9')
        {
            while(ord[s[i]]<=ord[semn[crt]] && semn[crt]!='(')
            {
                post[++crtp]=semn[crt--];
                post[++crtp]=',';
            }
            if(s[i]==')')
                --crt;
            else semn[++crt]=s[i];
            ++i;
        }
        else
        {
            while(s[i]>='0'&&s[i]<='9')
                post[++crtp]=s[i++];
            post[++crtp]=',';
        }
    }
    i=1;
    while(i<=crtp)
    {
        int nr=0;
        if(post[i]<'0' || post[i]>'9')
        {
            val=rez.top();
            rez.pop();
            rez.top()=slv(rez.top(),val,post[i]);
            ++i;
        }
        else
        {
            while(post[i]>='0' && post[i]<='9')
                nr=nr*10+post[i++]-'0';
            rez.push(nr);
        }
        i++;
    }
    printf("%d\n",rez.top());
    return 0;
}