Cod sursa(job #1884499)

Utilizator mihneacazCazacu Mihnea mihneacaz Data 18 februarie 2017 20:32:54
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include<cstdio>
#include<stack>
#include<cstring>
#include<cctype>
using namespace std;
stack <int> rez;
stack <char> op;
char s[100005];
int priority(char semn)
{
    int p;
    switch(semn)
    {
       case '+':
       case '-': p=1; break;
       case '*':
       case '/': p=2; break;
    }
    return p;
}
void calc()
{
    int x=rez.top();
    rez.pop();
    int y=rez.top();
    rez.pop();
    switch(op.top())
    {
        case '+': rez.push(x+y); break;
        case '-': rez.push(y-x); break;
        case '*': rez.push(x*y); break;
        case '/': rez.push(y/x); break;
    }
    op.pop();
}
int main()
{
    freopen("evaluare.in","r",stdin);
    freopen("evaluare.out","w",stdout);
    int n,nr,x;
    char y;
    gets(s);
    n=strlen(s);
    for(int i=0; i<n; i++)
    {
         if(!op.empty())
            y=op.top();
        if(s[i]=='(')
        {
            op.push('(');
            continue;
        }
        if(isdigit(s[i]))
        {
            nr=0;
            while(i<n && isdigit(s[i]))
            {
                nr=nr*10+s[i]-'0';
                i++;
            }
            i--;
            rez.push(nr);
             x=rez.top();
            continue;
        }
        if(s[i]==')')
        {
            while(!op.empty() && op.top()!='(')
                calc();
            x=rez.top();
            op.pop();
            continue;
        }
        int z=!op.empty();
        if(op.empty() || (op.empty() && op.top()=='('))
        {
            op.push(s[i]);
            continue;
        }
        if(op.empty() || (op.empty() && priority(s[i])>priority(op.top())))
        {
            op.push(s[i]);
            continue;
        }
        while(!op.empty() && op.top()!='(' && priority(s[i])<=priority(op.top()))
        {
            calc();
            x=rez.top();
        }
        op.push(s[i]);
     }
     while(!op.empty())
       calc();
    printf("%d\n",rez.top());
    return 0;
}