Pagini recente » Cod sursa (job #1518573) | Cod sursa (job #2358255) | Cod sursa (job #2650093) | Cod sursa (job #1510638) | Cod sursa (job #2732957)
#include <stdio.h>
#include <bits/stdc++.h>
#include <string>
#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) {
queue<char> op[2] = {{}, {}}; // + or -
// * or /
queue<int> num[2] = {{}, {}};
// cout << string(25, '-') << i << string(25, '-') << endl;
int d = 0;
while(i < s.size()) {
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[1].push(d);
} else if (s[i] == '+' || s[i] == '-') {
op[0].push(s[i]);
i++;
int res = num[1].front(); num[1].pop();
while(!op[1].empty()) {
int x = num[1].front(); num[1].pop();
char c = op[1].front(); op[1].pop();
if (c == '*') {
// cout << res << "*" << x << endl;
res = res * x;
}
else if (c == '/') {
// cout << res << "/" << x << endl;
res = res / x;
}
}
num[0].push(res);
} 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[1].push(d);
}
}
int res = num[1].front(); num[1].pop();
while(!op[1].empty()) {
int x = num[1].front(); num[1].pop();
char c = op[1].front(); op[1].pop();
if (c == '*') {
// cout << res << "*" << x << endl;
res = res * x;
}
else if (c == '/') {
// cout << res << "/" << x << endl;
res = res / x;
}
}
num[0].push(res);
res = num[0].front(); num[0].pop();
while(!op[0].empty()) {
int x = num[0].front(); num[0].pop();
char c = op[0].front(); op[0].pop();
if (c == '+') {
// cout << res << "+" << x << endl;
res = res + x;
}
else if (c == '-') {
// cout << res << "-" << x << endl;
res = res - x;
}
}
// cout << string(23, '=') << res << "===" << i << string(23, '=') << endl;
return Result{res, 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;
}