Pagini recente » Cod sursa (job #2464548) | Cod sursa (job #1896587) | Cod sursa (job #2280073) | Cod sursa (job #311348) | Cod sursa (job #1974872)
#include <iostream>
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
typedef long long ll;
const int NMax = 1e5 + 5;
int N,nrPost;
int prio[1<<8];
char str[NMax],*p;
struct elem {
int nr;
char op;
elem (int _nr = 0,char _op = '\0') {
nr = _nr;
op = _op;
}
}post[NMax];
int main() {
in>>(str+1);
str[0] = '(';
N = strlen(str);
str[N] = ')';
prio['('] = 1;
prio[')'] = 2;
prio['+'] = prio['-'] = 3;
prio['*'] = prio['/'] = 4;
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> aux;
for (int i=1;i<=nrPost;++i) {
if (post[i].op == '\0') {
aux.push(post[i].nr);
}
else {
int nr1,nr2,ans;
nr1 = aux.top(); aux.pop();
nr2 = aux.top(); aux.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;
}
aux.push(ans);
}
}
out<<aux.top()<<'\n';
return 0;
}