Pagini recente » Cod sursa (job #246466) | Cod sursa (job #2989312) | Cod sursa (job #3260678) | Cod sursa (job #2123950) | Cod sursa (job #2924320)
#include <bits/stdc++.h>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
stack < char > op;
queue < pair < int , char > > q;
string s;
stack < int > rez;
bool accept(char a, char b) {
if ((a=='+' || a=='-') && (b=='*' || b=='/')) return 1;
if ((a=='+' || a=='-') && (b=='+' || b=='-')) return 1;
if ((a=='*' || a=='/') && (b=='*' || b=='/')) return 1;
return 0;
}
int calc(int x1, int x2, char w) {
if (w=='+') return x1+x2;
if (w=='-') return x1-x2;
if (w=='*') return x1*x2;
if (w=='/') return x1/x2;
return 0;
}
void postfix() {
int i=0;
while (i<s.size()) {
if (s[i]=='(') {
op.push(s[i]);
i++;
}
else if ('0'<=s[i] && s[i]<='9') {
int x=0;
while ('0'<=s[i] && s[i]<='9') {
x = x*10+s[i]-'0';
i++;
}
q.push({x,0});
}
else if (s[i]==')') {
while (op.top()!='(') {
q.push({0,op.top()});
op.pop();
}
op.pop();
i++;
}
else {
while (accept(s[i],op.top())) {
q.push({0,op.top()});
op.pop();
}
op.push(s[i]);
i++;
}
}
}
void solve() {
while (!q.empty()) {
pair < int , char > x = q.front();
q.pop();
if (x.first) rez.push(x.first);
else {
int x2=rez.top(); rez.pop();
int x1=rez.top(); rez.pop();
rez.push(calc(x1,x2,x.second));
}
}
g << rez.top();
}
int main()
{
f >> s;
s = "(" + s + ")";
postfix();
solve();
return 0;
}