Cod sursa(job #1162024)

Utilizator SRaduRadu Szasz SRadu Data 31 martie 2014 16:30:07
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.68 kb
#include <fstream>
#include <cstring>
#include <vector>
#include <stack>
#include <iostream>
#include <cstdio>

using namespace std;

const int MAX = 100050;

int Ans;

char S[MAX];

stack<int> nrStk;
stack<char> opStk;

void citire() {
    ifstream in("evaluare.in");
    in >> S;
    in.close();
}

void popOperator() {
    int A = nrStk.top(); nrStk.pop();
    int B = nrStk.top(); nrStk.pop();
    int Ans;
    //cerr << "Extracting numbers " << A << " and " << B << " from the number stack\n";
    //cerr << "And operator " << opStk.top() << " from the operator stack\n";
    switch(opStk.top()) {
    case '+':
        Ans = B + A; 
        break;
    case '-':
        Ans = B - A;
        break;
    case '*':
        Ans = B * A;
        break;
    case '/':
        Ans = B / A;
        break;
    } opStk.pop();
    //cerr << "Pusing " << Ans << " to the number stack\n";
    nrStk.push(Ans);
}

void getReversePolishNotation() {
    int N = strlen(S);
    for(int i = 0; i < N; i++) {
        switch(S[i]) {
        case '(':
            //cerr << "Pushing ( to operator stack\n";
            opStk.push(S[i]);
            break;
        case ')':
            while(!opStk.empty() && opStk.top() != '(') {
                popOperator();
            } opStk.pop();
            break;
        case '+':
            while(!opStk.empty() && opStk.top() != '(') {
                popOperator();
            } opStk.push(S[i]);
            //cerr << "Pushing + to the operator stack\n";
            break;
        case '-':
            while(!opStk.empty() && opStk.top() != '(') {
                popOperator();
            } opStk.push(S[i]);
            //cerr << "Pushing - to the operator stack\n";
            break;
        case '*':
            while(!opStk.empty() && (opStk.top() == '*' || opStk.top() == '/')) {
                popOperator();
            } opStk.push(S[i]);
            //cerr << "Pushing * to the operator stack\n";
            break;
        case '/':
            while(!opStk.empty() && (opStk.top() == '*' || opStk.top() == '/')) {
                popOperator();
            } opStk.push(S[i]);
            //cerr << "Pushing / to the operator stack\n";
            break;
        default: 
            int X = 0;
            for(; i < N && isdigit(S[i]); i++)
                X = X * 10 + S[i] - '0';
            i--;
            nrStk.push(X);
            //cerr << "Pusing " << X << " to the number stack\n";
            break;
        }
    }
    while(!opStk.empty()) {
        popOperator();
    }
    Ans = nrStk.top();
}

void afisare() {
    ofstream out("evaluare.out");
    out << Ans << "\n";
    out.close();
}

int main() {    
    citire();
    getReversePolishNotation();
    afisare();
}