Cod sursa(job #2097860)

Utilizator MaligMamaliga cu smantana Malig Data 1 ianuarie 2018 19:21:00
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
#include <cstring>

using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");

#define ll long long
#define ull unsigned long long
#define ui unsigned int
#define pb push_back
#define mp make_pair
const int NMax = 1e5 + 5;
const ll inf = 1e18 + 5;
const ll valMax = 1e6 + 5;
using zint = short;

int N,nrPost;
char str[NMax];
short prio[300];
pair< char,int > post[NMax];

int main() {
    in>>(str+1);
    str[0] = '(';
    str[N = strlen(str)] = ')';

    prio['('] = 0;
    prio['+'] = prio['-'] = prio[')'] = 1;
    prio['*'] = prio['/'] = 2;

    stack<char> st;
    for (int i=0;i <= N;++i) {
        if (str[i] == '(') {
            st.push('(');
        }
        else if ('0' <= str[i] && str[i] <= '9') {
            int nr = 0;
            while ('0' <= str[i] && str[i] <= '9') {
                nr = nr * 10 + str[i++] - '0';
            }
            --i;

            post[++nrPost] = {0,nr};
        }
        else {
            while (prio[st.top()] >= prio[str[i]]) {
                post[++nrPost] = {st.top(),0};
                st.pop();
            }
            if (str[i] == ')') {
                st.pop();
            }
            else {
                st.push( str[i] );
            }
        }
    }

    stack<int> aux;
    for (int i=1;i <= nrPost;++i) {
        if (post[i].first == 0) {
            aux.push(post[i].second);
        }
        else {
            char op = post[i].first;
            int nr1 = aux.top(); aux.pop();
            int nr2 = aux.top(); aux.pop();

            switch(op) {
            case '+': { aux.push(nr2 + nr1); break; }
            case '-': { aux.push(nr2 - nr1); break; }
            case '*': { aux.push(nr2 * nr1); break; }
            case '/': { aux.push(nr2 / nr1); break; }
            }
        }
    }

    out<<aux.top();

    in.close();out.close();
    return 0;
}