Cod sursa(job #1969862)

Utilizator tudormaximTudor Maxim tudormaxim Data 18 aprilie 2017 18:05:55
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;

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

string S;
stack <int> Num;
stack <int> Op;

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

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

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

int main() {
    ios_base :: sync_with_stdio(false);
    getline(fin, S);
    Evaluate();
    fout << Num.top() << "\n";
    return 0;
}