Pagini recente » Cod sursa (job #1401578) | Cod sursa (job #3218322) | Cod sursa (job #2386878) | Cod sursa (job #841802) | Cod sursa (job #1974116)
#include <iostream>
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
const int strMax = 1e5 + 5;
int N,nrPost;
char str[strMax],prio[256];
struct elem {
int nr;
char c;
elem(int _nr = 0,int _c = '\0') {
nr = _nr;
c = _c;
}
}postfix[strMax];
int getNumber(int&);
int main() {
in>>(str+1);
N = strlen(str+1);
prio['('] = prio[')'] = 1;
prio['*'] = prio['/'] = 3;
prio['+'] = prio['-'] = 2;
int i = 1;
stack<char> st;
while (i <= N) {
if ('0' <= str[i] && str[i] <= '9') {
int nr = getNumber(i);
postfix[++nrPost] = elem(nr,'\0');
//++i;
}
else if (str[i] == '(') {
st.push('(');
//++i;
}
else if (str[i] == ')') {
while (st.top() != '(') {
postfix[++nrPost] = elem(0,st.top());
st.pop();
}
st.pop();
}
else {
if (!st.size() || prio[str[i]] > prio[st.top()]) {
st.push(str[i]);
}
else {
while (st.size() && prio[st.top()] >= prio[str[i]]) {
postfix[++nrPost] = elem(0,st.top());
st.pop();
}
st.push(str[i]);
}
}
++i;
}
while (st.size()) {
postfix[++nrPost] = elem(0,st.top());
st.pop();
}
for (int i=1;i<=nrPost;++i) {
if (postfix[i].c == '\0') {
//cout<<postfix[i].nr<<' ';
}
else {
//cout<<postfix[i].c<<' ';
}
}
//cout<<'\n';
stack<int> aux;
for (int i=1;i<=nrPost;++i) {
if (postfix[i].c == '\0') {
aux.push(postfix[i].nr);
}
else {
int nr1,nr2,res;
nr1 = aux.top(); aux.pop();
nr2 = aux.top(); aux.pop();
char op = postfix[i].c;
switch (op) {
case '+': {
res = nr2 + nr1;
break;
}
case '-': {
res = nr2 - nr1;
break;
}
case '*': {
res = nr2 * nr1;
break;
}
case '/': {
res = nr2 / nr1;
}
}
aux.push(res);
}
//cout<<aux.top()<<'\n';
}
out<<aux.top()<<'\n';
in.close();out.close();
return 0;
}
int getNumber(int& i) {
int nr = 0;
while ('0' <= str[i] && str[i] <= '9') {
nr = nr * 10 + (str[i]-'0');
++i;
}
--i;
return nr;
}