Advertisement
Guest User

Untitled

a guest
Oct 7th, 2021
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long double;  // it was long long, but I was wrong
  5. using sit = string::const_iterator;
  6.  
  7. #define clog if (0) cerr
  8.  
  9. ll x;
  10. ll parse_x(sit& s) {
  11.     clog << "x " << *s << endl;
  12.     assert(*s == 'x');
  13.     ++s;
  14.     return x;
  15. }
  16.  
  17. // parse number (with leading zero)
  18. // also support nagetive number
  19. ll parse_num(sit& s) {
  20.     clog << "num " << *s << endl;
  21.     assert(isdigit(*s));
  22.     ll num = 0;
  23.     while (isdigit(*s)) {
  24.         num = num * 10 + *s - '0';
  25.         ++s;
  26.     }
  27.     return num;
  28. }
  29.  
  30. ll parse_atom(sit& s) {
  31.     clog << "atom " << *s << endl;
  32.     if (*s == '-') return -parse_atom(++s);
  33.     if (*s == '+') return parse_atom(++s);
  34.     if (*s == 'x') return parse_x(s);
  35.     return parse_num(s);
  36. }
  37.  
  38. // term is atoms with * and /
  39. ll parse_term(sit& s) {
  40.     clog << "term " << *s << endl;
  41.     ll ans = parse_atom(s);
  42.     while (*s == '/' or *s == '*') {
  43.         char ch = *s;
  44.         auto cur_atom = parse_atom(++s);
  45.         if (ch == '/') ans /= cur_atom;
  46.         else ans *= cur_atom;
  47.     }
  48.     return ans;
  49. }
  50.  
  51. // expr is terms with + and -
  52. ll parse_expr(sit& s) {
  53.     clog << "expr " << *s << endl;
  54.     ll ans = parse_term(s);
  55.     while (*s == '+' or *s == '-') {
  56.         char ch = *s;
  57.         auto cur_term = parse_term(++s);
  58.         if (ch == '-') ans -= cur_term;
  59.         else ans += cur_term;
  60.     }
  61.     return ans;
  62. }
  63.  
  64. ll evaluate(const string& s, ll the_x) {
  65.     x = the_x;
  66.     sit s_it = s.begin() + 5;
  67.     auto ans = parse_expr(s_it);
  68.     assert(*s_it == 0);
  69.     return ans;
  70. }
  71.  
  72. int main() {
  73.     cin.tie(0)->sync_with_stdio(0);
  74.     string func;
  75.     cin >> func;
  76.     int q;
  77.     cin >> q;
  78.     while (q--) {
  79.         ll the_x;
  80.         cin >> the_x;
  81.         auto ans = evaluate(func, the_x);
  82.         cout << (long long)ans << '\n';
  83.     }
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement