Cod sursa(job #1027602)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 12 noiembrie 2013 21:22:02
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.2 kb
#include <fstream>
#include <stack>
#include <cstring>
#include <sstream>

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

bool isDigit(char c) {
    return (c <= '9' && c >= '0');
}

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

int RPN(char *sz) {
    std::stack<char> myS;
    std::stack<int> myN;
    int a, b;
    char c;
    unsigned d = strlen(sz);
    for(unsigned i = 0; i < d; ) {
        if(isDigit(sz[i])) {
            std::stringstream ss;
            while(isDigit(sz[i])) {
                ss << sz[i];
                i++;
            }
            int aux;
            ss >> aux;
            myN.push(aux);
        } else {
            if(sz[i] == '(') {
                myS.push('(');
            } else if(sz[i] == ')') {
                while(!myS.empty() && myS.top() != '(') {
                    c = myS.top();
                    myS.pop();
                    b = myN.top();
                    myN.pop();
                    a = myN.top();
                    myN.pop();
                    myN.push(operate(a, b, c));
                }
                myS.pop();
            } else {
                while(!myS.empty() && priority(myS.top()) >= priority(sz[i])) {
                    c = myS.top();
                    myS.pop();
                    b = myN.top();
                    myN.pop();
                    a = myN.top();
                    myN.pop();
                    myN.push(operate(a, b, c));
                }
                myS.push(sz[i]);
            }
            i++;
        }
    }
    while(!myS.empty()) {
        c = myS.top();
        myS.pop();
        b = myN.top();
        myN.pop();
        a = myN.top();
        myN.pop();
        myN.push(operate(a, b, c));
    }
    return myN.top();
}

int main() {
    freopen("evaluare.in", "r", stdin);
    freopen("evaluare.out", "w", stdout);
    char *str = new char[100000];
    gets(str);
    printf("%d", RPN(str));
    return 0;
}