Cod sursa(job #1987268)

Utilizator MaligMamaliga cu smantana Malig Data 30 mai 2017 08:26:57
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stack>
#include <cstring>

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

#define ll long long
#define pb push_back
const int strMax = 1e5 + 5;
const ll inf = 9e18 + 5;

int N,nrPost;
int prio[(1<<8) + 5];
char str[strMax];

struct elem {
    int nr;
    char op;
    elem(int _nr = 0,char _op = '\0') {
        nr = _nr;
        op = _op;
    }
}post[strMax];

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

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

    stack<char> ops;
    for (int i=0;i < N;++i) {
        if (str[i] == '(') {
            ops.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] = elem(nr);
        }
        else {
            while (prio[ops.top()] >= prio[str[i]]) {
                post[++nrPost] = elem(0,ops.top());
                ops.pop();
            }
            if (str[i] == ')') {
                ops.pop();
            }
            else {
                ops.push(str[i]);
            }
        }
    }

    stack<int> num;
    for (int i=1;i <= nrPost;++i) {
        if (post[i].op == '\0') {
            num.push(post[i].nr);
        }
        else {
            int nr1,nr2,ans;
            nr1 = num.top(); num.pop();
            nr2 = num.top(); num.pop();

            char op = post[i].op;
            switch (op) {
            case '+': ans = nr2+nr1; break;
            case '-': ans = nr2-nr1; break;
            case '*': ans = nr2*nr1; break;
            case '/': ans = nr2/nr1; break;
            }

            num.push(ans);
        }
    }
    out<<num.top()<<'\n';

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