Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- using ll = long double; // it was long long, but I was wrong
- using sit = string::const_iterator;
- #define clog if (0) cerr
- ll x;
- ll parse_x(sit& s) {
- clog << "x " << *s << endl;
- assert(*s == 'x');
- ++s;
- return x;
- }
- // parse number (with leading zero)
- // also support nagetive number
- ll parse_num(sit& s) {
- clog << "num " << *s << endl;
- assert(isdigit(*s));
- ll num = 0;
- while (isdigit(*s)) {
- num = num * 10 + *s - '0';
- ++s;
- }
- return num;
- }
- ll parse_atom(sit& s) {
- clog << "atom " << *s << endl;
- if (*s == '-') return -parse_atom(++s);
- if (*s == '+') return parse_atom(++s);
- if (*s == 'x') return parse_x(s);
- return parse_num(s);
- }
- // term is atoms with * and /
- ll parse_term(sit& s) {
- clog << "term " << *s << endl;
- ll ans = parse_atom(s);
- while (*s == '/' or *s == '*') {
- char ch = *s;
- auto cur_atom = parse_atom(++s);
- if (ch == '/') ans /= cur_atom;
- else ans *= cur_atom;
- }
- return ans;
- }
- // expr is terms with + and -
- ll parse_expr(sit& s) {
- clog << "expr " << *s << endl;
- ll ans = parse_term(s);
- while (*s == '+' or *s == '-') {
- char ch = *s;
- auto cur_term = parse_term(++s);
- if (ch == '-') ans -= cur_term;
- else ans += cur_term;
- }
- return ans;
- }
- ll evaluate(const string& s, ll the_x) {
- x = the_x;
- sit s_it = s.begin() + 5;
- auto ans = parse_expr(s_it);
- assert(*s_it == 0);
- return ans;
- }
- int main() {
- cin.tie(0)->sync_with_stdio(0);
- string func;
- cin >> func;
- int q;
- cin >> q;
- while (q--) {
- ll the_x;
- cin >> the_x;
- auto ans = evaluate(func, the_x);
- cout << (long long)ans << '\n';
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement