Cod sursa(job #1654244)

Utilizator PaulCbnCiobanu Paul PaulCbn Data 16 martie 2016 21:53:58
Problema Evaluarea unei expresii Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <stack>
#include <cstring>

using namespace std;

stack<int> r;

bool HigherPriority(char a,char b)
{
    if(a=='+'||a=='-')
    {
        if(b=='+'||b=='-')
            return 1;
        return 0;
    }
    return 1;
}

int calc(int op1,int op2,char ope)
{
    if(ope == '-')
        return op1-op2;
    if(ope == '+')
        return op1+op2;
    if(ope == '*')
        return op1*op2;
    if(ope == '/')
        return op1/op2;

}

void infixToPostfix(char exp[])
{

    int N = strlen(exp)-1,k=0;
    stack<char> s;

    for(int i=0; i<=N; i++)
    {
        if(exp[i]=='(')
        {
            s.push(exp[i]);
            continue;
        }
        if(exp[i]==')')
        {
            while(s.top()!='(')
            {
                int op1 = r.top(); r.pop();
                int op2 = r.top(); r.pop();
                char ope = s.top();s.pop();

                r.push(calc(op1,op2,ope));
            }
            s.pop();
            continue;
        }
        if(isdigit(exp[i]))
        {
            r.push(atoi(exp+i));
            while(isdigit(exp[i+1]))i++;
            continue;
        }
        while(!s.empty()&&HigherPriority(s.top(),exp[i]))
        {
            if(s.top()=='(')
                break;

            int op1 = r.top(); r.pop();
            int op2 = r.top(); r.pop();
            char ope = s.top();s.pop();

            r.push(calc(op1,op2,ope));


        }

        s.push(exp[i]);

    }
    while(!s.empty())
    {
        int op1 = r.top(); r.pop();
        int op2 = r.top(); r.pop();
        char ope = s.top();s.pop();

        r.push(calc(op2,op1,ope));

    }

}

int main()
{
    freopen("evaluare.in","r",stdin);
    freopen("evaluare.out","w",stdout);
    char s[100],*s1;
    scanf("%s",s);

    infixToPostfix(s);
    printf("%d",r.top());

    return 0;
}