fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define all(ac) ac.begin(), ac.end()
  4. #define fi first
  5. #define se second
  6. #define pii pair <int, int>
  7. #define task "tet"
  8. #define db double
  9. #define pb push_back
  10. #define eb emplace_back
  11. #define pci pair <char, int>
  12. #define int long long
  13.  
  14. int prio(char a) {
  15. if(a == '(' || a == ')') return 0;
  16. if(a == '+' || a == '-') return 1;
  17. return 2;
  18. }
  19.  
  20. void add(char oper, stack <char> &stk, queue <pci> &q) {
  21. while(stk.size() && prio(stk.top()) >= prio(oper)) {
  22. q.push({stk.top(), 0});
  23. stk.pop();
  24. }
  25. stk.push(oper);
  26. return;
  27. }
  28.  
  29. int32_t main() {
  30. ios::sync_with_stdio(false);
  31. cin.tie(0), cout.tie(0);
  32. if(fopen(task".inp", "r")) {
  33. freopen(task".inp", "r", stdin);
  34. freopen(task".out", "w", stdout);
  35. }
  36.  
  37. string s; cin >> s;
  38. s = "(" + s + ")";
  39. int p, M; cin >> p >> M;
  40.  
  41. stack <char> oper;
  42. queue <pci> q;
  43. bool ok = false;
  44. int cur = 0;
  45. for(char c : s) {
  46. if(c >= '0' && c <= '9') ok = true, cur = cur * 10 + c - '0';
  47. else {
  48. if(ok == true) q.push({'!', cur}), cur = 0, ok = false;
  49. if(c == '(') oper.push(c);
  50. else
  51. if(c == ')') {
  52. while(true) {
  53. char op = oper.top();
  54. oper.pop();
  55. if(op == '(') break;
  56. q.push({op, 0});
  57. }
  58. }
  59. else
  60. if(c == 'x') q.push({c, 0});
  61. else add(c, oper, q);
  62. }
  63. }
  64.  
  65. stack <pii> stk;
  66. while(q.size()) {
  67. pci cur = q.front();
  68. q.pop();
  69. if(cur.fi == '!') stk.push({0, cur.se});
  70. else
  71. if(cur.fi == 'x') stk.push({1, 0});
  72. else {
  73. pii b = stk.top(); stk.pop();
  74. pii a = stk.top(); stk.pop();
  75.  
  76. pii res;
  77. if(cur.fi == '+') res.fi = a.fi + b.fi, res.se = a.se + b.se;
  78. else
  79. if(cur.fi == '-') res.fi = a.fi - b.fi, res.se = a.se - b.se;
  80. else {
  81. res.fi = a.fi * b.se + b.fi * a.se;
  82. res.se = b.se * a.se;
  83. }
  84. stk.push(res);
  85. }
  86. }
  87.  
  88. pii val = stk.top();
  89. int x = 0;
  90. while(true) {
  91. int w = val.fi * x + val.se;
  92. if(w % M == p) return cout << x, 0;
  93. x++;
  94. }
  95. return 0;
  96. }
Success #stdin #stdout 0.01s 5316KB
stdin
3*(x+(x+4)*5)
1 7
stdout
1