Pagini recente » Cod sursa (job #1658549) | Cod sursa (job #2944857) | Cod sursa (job #2625828) | Cod sursa (job #1674933) | Cod sursa (job #1996621)
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <algorithm>
#include <stack>
#include <cstring>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
const int NMax = 1e5 + 5;
int N,nrPost;
int prio[300];
char str[NMax];
struct elem {
int val;
char op;
elem(int _val = 0,char _op = '\0') {
val = _val;
op = _op;
}
}post[NMax];
int main() {
in>>(str+1);
str[0] = '(';
str[N = strlen(str)] = ')';
++N;
prio['('] = 1;
prio['+'] = prio['-'] = prio[')'] = 2;
prio['*'] = prio['/'] = 3;
stack<char> op;
for (int i=0;i < N;++i) {
if (str[i] == '(') {
op.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[op.top()] >= prio[str[i]]) {
post[++nrPost] = elem(0,op.top());
op.pop();
}
if (str[i] == ')') {
op.pop();
}
else {
op.push(str[i]);
}
}
}
stack<int> aux;
for (int i=1;i <= nrPost;++i) {
if (post[i].op == '\0') {
aux.push(post[i].val);
}
else {
int nr1,nr2,ans;
char op = post[i].op;
nr1 = aux.top(); aux.pop();
nr2 = aux.top(); aux.pop();
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';
in.close();out.close();
return 0;
}