Cod sursa(job #1450788)

Utilizator PlatonVPlaton Vlad PlatonV Data 14 iunie 2015 18:28:13
Problema Evaluarea unei expresii Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.69 kb
#include <queue>
#include <stack>
#include <stdio.h>

using namespace std;

FILE* g = fopen("evaluare.out", "w");

long result;

bool isOp(char c)
{
    if (c == '*' || c == '/' || c == '+' || c== '-' || c == '(' || c == ')')
        return true;
    return false;
}

long calc(int o1, int o2, char op)
{
    switch(op)
    {
        case '*':
            return o1 * o2;
            break;
        case '/':
            return o1 / o2;
            break;
        case '-':
            return o1 - o2;
            break;
        case '+':
            return o1 + o2;
            break;
    }
}

int priority(char c)
{
    if (c == '*' || c == '/')
    {
        return 2;
    }
    if (c == '+' || c == '-')
    {
        return 1;
    }
    return 0;
}

int main()
{
    freopen("evaluare.in", "r", stdin);
    freopen("evaluare.out", "w", stdout);

    char c;
    int nr = 0;
    bool da = false;
    stack<char> s;
    queue<char> q;
    while (scanf("%c", &c) != EOF)
    {
        if (isOp(c))
        {
            q.push(' ');
            if (c == '(')
                s.push(c);
            else
            {
                if (c == ')')
                {
                    while (s.top() != '(')
                    {
                        q.push(s.top());;
                        q.push(' ');
                        s.pop();
                    }
                    s.pop();
                }
                else
                {
                    while (!s.empty() && priority(c) <= priority(s.top()))
                    {
                        q.push(s.top());;
                        q.push(' ');
                        s.pop();
                    }
                    s.push(c);
                }
            }

        }
        else
        {
            if (c >= '0' && c <='9')
                q.push(c);
        }
    }
    while(!s.empty())
    {
        q.push(s.top());;
        s.pop();
    }
    
    stack<int> st;
    while (!q.empty())
    {
        c = q.front();
        q.pop();

        if (isOp(c))
        {
            int op2 = st.top();
            st.pop();
            int op1 = st.top();
            st.pop();
            st.push(calc(op1, op2, c));
        }
        else
        {
            if (c != ' ')
            {
                nr = nr * 10 + (c - '0');
                da = true;
            }
            else
            {
                if (da)
                {
                    st.push(nr);
                }
                nr = 0;
                da = false;
            }
        }
    }

    printf("%d", st.top());

    return 0;
}