Cod sursa(job #2003506)

Utilizator roitainNiculae Cristian roitain Data 23 iulie 2017 00:15:11
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.4 kb
#include<iostream>
#include<vector>
#include<stack>
#include<cstring>
#include<cstdio>
using namespace std;

int priority(char a){
    // 3 high priority - 2 medium priority - 1 low priority
    if(a=='(' || a==')')
        return 3;
    if(a=='*' || a=='/')
        return 2;
    else return 1;
}

bool isOperator(char a){
    if(strchr("()*/+-",a))
        return 1;
}

string infix;
string postfix;
stack<char> order;

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

    int N = infix.size();

    for(int i = 0; i < N;){

        while(infix[i] == ' ')
            ++i;

        if(!isOperator(infix[i])){

            while(!isOperator(infix[i]))
                postfix += infix[i++];

            postfix += ' ';

        }else if(infix[i] == '('){
            order.push('(');
            ++i;

        }else if(infix[i] == ')'){
            while(order.top() != '('){
                postfix += order.top();
                postfix += ' ';
                order.pop();
            }
            order.pop();
            ++i;

        }else if(isOperator(infix[i])){
            if(order.empty()){
                order.push(infix[i]);
            }else{
                while(!order.empty() && order.top() != '(' && priority(order.top()) >= priority(infix[i])){
                    postfix += order.top();
                    postfix += ' ';
                    order.pop();
                }
                order.push(infix[i]);

            }
            ++i;

        }
    }

    while(!order.empty()){
        postfix += order.top();
        postfix += ' ';
        order.pop();
    }
    //cout<<postfix;
    int M = postfix.length();
    int a,b;
    stack<int> st;

    for(int i = 0; i < M; i+=2){
        if(isOperator(postfix[i])){
            a = st.top();
            st.pop();
            b = st.top();
            st.pop();

            switch(postfix[i]){
                case '+': st.push(a+b);break;
                case '-': st.push(b-a);break;
                case '*': st.push(b*a);break;
                case '/': st.push(b/a);break;
            }
        }else{
            a=postfix[i]-'0';
            while(postfix[i+1]!=' ')
                a = a*10 + postfix[++i]-'0';
            st.push(a);
        }
    }

    cout<<st.top();

    return 0;
}