Cod sursa(job #1870957)

Utilizator tudormaximTudor Maxim tudormaxim Data 7 februarie 2017 00:05:52
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;

ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");

const int maxn = 1e5 + 5;
stack <int> Nr;
stack <char> Op;
string S;

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

inline void Operation() {
    char op = Op.top(); Op.pop();
    int y = Nr.top(); Nr.pop();
    int x = Nr.top(); Nr.pop();
    if (op == '+') {
        Nr.push(x + y);
    } else if (op == '-') {
        Nr.push(x - y);
    } else if (op == '*') {
        Nr.push(x * y);
    } else if (op == '/') {
        Nr.push(x / y);
    }

}

void Solve() {
    int i, priority, val;
    Op.push('#');
    for (i = 0; i < S.size(); i++) {
        if (S[i] == '(') {
            Op.push(S[i]);
        } else if (S[i] == ')') {
            while (Op.top() != '(') {
                  Operation();
            }
            Op.pop();
        } else {
            priority = Priority(S[i]);
            if (priority > 0) {
                while (Priority(Op.top()) >= priority) {
                    Operation();
                }
                Op.push(S[i]);
            } else {
                val = 0;
                while (S[i] >= '0' && S[i] <= '9') {
                    val = (val << 1) + (val << 3) + (S[i] - '0');
                    i++;
                }
                Nr.push(val);
                i--;
            }
        }
    }
    while (Op.top() != '#') {
        Operation();
    }
}

int main() {
    ios_base :: sync_with_stdio (false);
    getline(fin, S);
    Solve();
    fout << Nr.top();
    fin.close();
    fout.close();
    return 0;
}