Cod sursa(job #791046)

Utilizator toranagahVlad Badelita toranagah Data 22 septembrie 2012 19:00:24
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.41 kb
#include <fstream>
#include <string>
#include <stack>
#include <queue>
#include <cctype>
#include <iostream>

const int PLUS = 1000000002;
const int MINUS = 1000000003;
const int MUL = 1000000004;
const int DIV = 1000000005;

using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
stack<int> st;
queue<int> qu;

inline int precedence(char c);
inline int optoint(int t);

int main(int argc, char const *argv[])
{
    getline(fin, s);
    int l = s.size();
    char c;
    int x;
    for (int i = 0; i < l; ++i) {
        c = s[i];
        x = 0;
        if (isdigit(c)) {
            while(i < l && isdigit(s[i])) {
                x = x * 10 + (s[i] - '0');
                ++i;
            }
            --i;
            qu.push(x);
        } else if (c == ')') {
            while (!st.empty() && st.top() != '(') {
                qu.push(optoint(st.top()));
                st.pop();
            }
            st.pop();
        } else if (c == '(') {
            st.push((int)c); 
        } else {
            while (!st.empty() && precedence(c) <= precedence(st.top())) {

                qu.push(optoint(st.top()));
                st.pop();
            }
            st.push((int)c);
        }
    }
    while (!st.empty()) {
        qu.push(optoint(st.top()));
        st.pop();
    }

    int result = 0;
    int temp;
    while (!qu.empty()) {
        x = qu.front();
        //fout << x << endl;
        if (x < 1000000001) {
            st.push(x);
        } else if (x == PLUS) {
            temp = st.top();
            st.pop();
            st.top() += temp;
        } else if (x == MINUS) {
            temp = st.top();
            st.pop();
            st.top() -= temp;
        } else if (x == MUL) {
            temp = st.top();
            st.pop();
            st.top() *= temp;
        } else if (x == DIV) {
            temp = st.top();
            st.pop();
            st.top() /= temp;
        }
        qu.pop();
    }
    result = st.top();
    st.pop();
    fout << result;
    return 0;
}

inline int optoint(int t) {
    switch (t) {
        case '+':
            return PLUS;
        case '-':
            return MINUS;
        case '*':
            return MUL;
        case '/':
            return DIV;
        default:
            return -1;
    }
}

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