Pagini recente » Cod sursa (job #2396605) | Cod sursa (job #247782) | Cod sursa (job #234975) | Cod sursa (job #831216) | Cod sursa (job #2732900)
#include <stdio.h>
#include <bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
// const int INF = 0x3f3f3f3f;
ifstream fin {"evaluare.in"};
ofstream fout {"evaluare.out"};
struct Result {
int num;
size_t pos;
};
Result eval(const string &s, size_t i) {
stack<char> op[2]; // + or -
// * or /
stack<int> num;
int d = 0;
while(i < s.size()) {
bool process = false;
if (s[i] == ')') {
i++;
break;
} else if ('0' <= s[i] && s[i] <= '9') {
d = 0;
while('0' <= s[i] && s[i] <= '9') {
d = d*10 + s[i] - '0';
i++;
}
num.push(d);
process = true;
} else if (s[i] == '+' || s[i] == '-') {
op[0].push(s[i]);
i++;
} else if (s[i] == '*' || s[i] == '/') {
op[1].push(s[i]);
i++;
} else if (s[i] == '(') {
i++;
auto result = eval(s, i);
d = result.num;
i = result.pos;
num.push(d);
process = true;
}
if (process) {
for(int x = 1; x >= 0; x--) {
auto &opp = op[x];
while(!opp.empty()) {
char c = opp.top(); opp.pop();
int y = num.top(); num.pop();
int x = num.top(); num.pop();
switch(c) {
case '+':
num.push(x+y); break;
case '-':
num.push(x-y); break;
case '*':
num.push(x*y); break;
case '/':
num.push(x/y); break;
}
}
}
}
}
return Result{num.top(), i};
}
int main(void) {
// freopen("evaluare.in", "r", stdin);
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
string str;
fin >> str;
auto res = eval(str, 0);
fout << res.num << '\n';
return 0;
}